Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Added sorting, searching and filtering to Checkout (#8381)

Ivan Prlićdf2ee43e2d38
diff --git a/saleor/graphql/checkout/filters.py b/saleor/graphql/checkout/filters.py
new file mode 100644
index 0000000000..720e05bfbf
--- /dev/null
+++ b/saleor/graphql/checkout/filters.py
@@ -0,0 +1,93 @@
+from uuid import UUID
+
+import django_filters
+from django.db.models import Exists, OuterRef, Q
+from graphene_django.filter import GlobalIDMultipleChoiceFilter
+
+from ...account.models import User
+from ...checkout.models import Checkout
+from ...payment.models import Payment
+from ..channel.types import Channel
+from ..core.filters import MetadataFilterBase, ObjectTypeFilter
+from ..core.types import FilterInputObjectType
+from ..core.types.common import DateRangeInput
+from ..core.utils import from_global_id_or_error
+from ..utils import resolve_global_ids_to_primary_keys
+from ..utils.filters import filter_range_field
+
+
+def get_checkout_token_from_query(value):
+ try:
+ return UUID(value, version=4)
+ except ValueError:
+ # If it's a value error, then the string
+ # is not a valid hex code for a UUID.
+ return None
+
+
+def get_payment_id_from_query(value):
+ try:
+ return from_global_id_or_error(value, only_type="Payment")[1]
+ except Exception:
+ return None
+
+
+def filter_checkout_by_payment(qs, payment_id):
+ if payment_id:
+ payments = Payment.objects.filter(pk=payment_id).values("id")
+ qs = qs.filter(Q(Exists(payments.filter(checkout_id=OuterRef("token")))))
+ return qs
+
+
+def filter_created_range(qs, _, value):
+ return filter_range_field(qs, "created__date", value)
+
+
+def filter_customer(qs, _, value):
+ users = User.objects.filter(
+ Q(email__ilike=value) | Q(first_name__ilike=value) | Q(last_name__ilike=value)
+ ).values("pk")
+
+ return qs.filter(Q(Exists(users.filter(id=OuterRef("user_id")))))
+
+
+def filter_channels(qs, _, values):
+ if values:
+ _, channels_ids = resolve_global_ids_to_primary_keys(values, Channel)
+ qs = qs.filter(channel_id__in=channels_ids)
+ return qs
+
+
+def filter_checkout_search(qs, _, value):
+ if payment_id := get_payment_id_from_query(value):
+ return filter_checkout_by_payment(qs, payment_id)
+
+ users = User.objects.filter(
+ Q(email__ilike=value) | Q(first_name__ilike=value) | Q(last_name__ilike=value)
+ ).values("pk")
+
+ filter_option = Q(Exists(users.filter(id=OuterRef("user_id"))))
+
+ if checkout_id := get_checkout_token_from_query(value):
+ filter_option |= Q(token=checkout_id)
+
+ payments = Payment.objects.filter(psp_reference=value).values("id")
+ filter_option |= Q(Exists(payments.filter(checkout_id=OuterRef("token"))))
+
+ return qs.filter(filter_option)
+
+
+class CheckoutFilter(MetadataFilterBase):
+ customer = django_filters.CharFilter(method=filter_customer)
+ created = ObjectTypeFilter(input_class=DateRangeInput, method=filter_created_range)
+ search = django_filters.CharFilter(method=filter_checkout_search)
+ channels = GlobalIDMultipleChoiceFilter(method=filter_channels)
+
+ class Meta:
+ model = Checkout
+ fields = ["customer", "created", "search"]
+
+
+class CheckoutFilterInput(FilterInputObjectType):
+ class Meta:
+ filterset_class = CheckoutFilter
diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.py
index 85ca102fc7..b059f39742 100644
--- a/saleor/graphql/checkout/schema.py
+++ b/saleor/graphql/checkout/schema.py
@@ -1,11 +1,12 @@
import graphene
from ...core.permissions import CheckoutPermissions
-from ..core.descriptions import DEPRECATED_IN_3X_FIELD
-from ..core.fields import BaseDjangoConnectionField, PrefetchingConnectionField
+from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD
+from ..core.fields import FilterInputConnectionField, PrefetchingConnectionField
from ..core.scalars import UUID
from ..decorators import permission_required
from ..payment.mutations import CheckoutPaymentCreate
+from .filters import CheckoutFilterInput
from .mutations import (
CheckoutAddPromoCode,
CheckoutBillingAddressUpdate,
@@ -24,6 +25,7 @@ from .mutations import (
CheckoutShippingMethodUpdate,
)
from .resolvers import resolve_checkout, resolve_checkout_lines, resolve_checkouts
+from .sorters import CheckoutSortingInput
from .types import Checkout, CheckoutLine
@@ -34,12 +36,16 @@ class CheckoutQueries(graphene.ObjectType):
token=graphene.Argument(UUID, description="The checkout's token."),
)
# FIXME we could optimize the below field
- checkouts = BaseDjangoConnectionField(
+ checkouts = FilterInputConnectionField(
Checkout,
- description="List of checkouts.",
+ sort_by=CheckoutSortingInput(description=f"{ADDED_IN_31} Sort checkouts."),
+ filter=CheckoutFilterInput(
+ description=f"{ADDED_IN_31} Filtering options for checkouts."
+ ),
channel=graphene.String(
description="Slug of a channel for which the data should be returned."
),
+ description="List of checkouts.",
)
checkout_lines = PrefetchingConnectionField(
CheckoutLine, description="List of checkout lines."
diff --git a/saleor/graphql/checkout/sorters.py b/saleor/graphql/checkout/sorters.py
new file mode 100644
index 0000000000..a35ec42e72
--- /dev/null
+++ b/saleor/graphql/checkout/sorters.py
@@ -0,0 +1,35 @@
+import graphene
+from django.db.models import CharField, ExpressionWrapper, OuterRef, QuerySet, Subquery
+
+from ...payment.models import Payment
+from ..core.types import SortInputObjectType
+
+
+class CheckoutSortField(graphene.Enum):
+ CREATION_DATE = ["created", "pk"]
+ CUSTOMER = ["billing_address__last_name", "billing_address__first_name", "pk"]
+ PAYMENT = ["last_charge_status", "pk"]
+
+ @property
+ def description(self):
+ if self.name in CheckoutSortField.__enum__._member_names_:
+ sort_name = self.name.lower().replace("_", " ")
+ return f"Sort checkouts by {sort_name}."
+ raise ValueError("Unsupported enum value: %s" % self.value)
+
+ @staticmethod
+ def qs_with_payment(queryset: QuerySet, **_kwargs) -> QuerySet:
+ subquery = Subquery(
+ Payment.objects.filter(checkout_id=OuterRef("pk"))
+ .order_by("-pk")
+ .values_list("charge_status")[:1]
+ )
+ return queryset.annotate(
+ last_charge_status=ExpressionWrapper(subquery, output_field=CharField())
+ )
+
+
+class CheckoutSortingInput(SortInputObjectType):
+ class Meta:
+ sort_enum = CheckoutSortField
+ type_name = "checkouts"
diff --git a/saleor/graphql/checkout/tests/test_checkout_filters.py b/saleor/graphql/checkout/tests/test_checkout_filters.py
new file mode 100644
index 0000000000..1e06623f6a
--- /dev/null
+++ b/saleor/graphql/checkout/tests/test_checkout_filters.py
@@ -0,0 +1,395 @@
+import uuid
+from datetime import date, timedelta
+
+import graphene
+import pytest
+from freezegun import freeze_time
+
+from ....account.models import User
+from ....checkout.models import Checkout
+from ....payment.models import ChargeStatus, Payment
+from ...tests.utils import get_graphql_content
+
+
+def checkout_query_with_filter():
+ query = """
+ query ($filter: CheckoutFilterInput!, ) {
+ checkouts(first: 5, filter:$filter) {
+ totalCount
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+ return query
+
+
+def test_checkout_query_with_filter_channels_with_one_channel(
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkouts_list,
+ channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ variables = {"filter": {"channels": [channel_id]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ checkout_query_with_filter,
+ variables,
+ permissions=(permission_manage_checkouts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ checkouts_list = content["data"]["checkouts"]["edges"]
+ assert len(checkouts_list) == 3
+
+
+def test_checkout_query_with_filter_channels_without_channel(
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkouts_list,
+):
+ # given
+ variables = {"filter": {"channels": []}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ checkout_query_with_filter,
+ variables,
+ permissions=(permission_manage_checkouts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ checkouts_list = content["data"]["checkouts"]["edges"]
+ assert len(checkouts_list) == 5
+
+
+def test_checkout_query_with_filter_channels_with_many_channel(
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkouts_list,
+ channel_USD,
+ channel_PLN,
+ other_channel_USD,
+):
+ # given
+ Checkout.objects.create(channel=other_channel_USD)
+ channel_other_usd_id = graphene.Node.to_global_id("Channel", other_channel_USD.pk)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {"filter": {"channels": [channel_pln_id, channel_other_usd_id]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ checkout_query_with_filter,
+ variables,
+ permissions=(permission_manage_checkouts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ checkout_list = content["data"]["checkouts"]["edges"]
+ assert len(checkout_list) == 3
+
+
+def test_checkout_query_with_filter_channels_with_empty_channel(
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ checkouts_list,
+ other_channel_USD,
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", other_channel_USD.pk)
+ variables = {"filter": {"channels": [channel_id]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ checkout_query_with_filter,
+ variables,
+ permissions=(permission_manage_checkouts,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ checkouts_list = content["data"]["checkouts"]["edges"]
+ assert len(checkouts_list) == 0
+
+
+ "checkouts_filter, count",
+ [
+ (
+ {
+ "created": {
+ "gte": str(date.today() - timedelta(days=3)),
+ "lte": str(date.today()),
+ }
+ },
+ 1,
+ ),
+ ({"created": {"gte": str(date.today() - timedelta(days=3))}}, 1),
+ ({"created": {"lte": str(date.today())}}, 2),
+ ({"created": {"lte": str(date.today() - timedelta(days=3))}}, 1),
+ ({"created": {"gte": str(date.today() + timedelta(days=1))}}, 0),
+ ],
+)
+def test_checkout_query_with_filter_created(
+ checkouts_filter,
+ count,
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ channel_USD,
+):
+ Checkout.objects.create(channel=channel_USD)
+ with freeze_time("2012-01-14"):
+ Checkout.objects.create(channel=channel_USD)
+ variables = {"filter": checkouts_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+ content = get_graphql_content(response)
+ checkouts_list = content["data"]["checkouts"]["edges"]
+
+ assert len(checkouts_list) == count
+
+
+ "checkouts_filter, user_field, user_value",
+ [
+ ({"customer": "admin"}, "email", "[email protected]"),
+ ({"customer": "John"}, "first_name", "johnny"),
+ ({"customer": "Snow"}, "last_name", "snow"),
+ ],
+)
+def test_checkouts_query_with_filter_customer_fields(
+ checkouts_filter,
+ user_field,
+ user_value,
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ customer_user,
+ channel_USD,
+):
+ setattr(customer_user, user_field, user_value)
+ customer_user.save()
+ customer_user.refresh_from_db()
+
+ checkout = Checkout(
+ user=customer_user, token=str(uuid.uuid4()), channel=channel_USD
+ )
+ Checkout.objects.bulk_create(
+ [checkout, Checkout(token=str(uuid.uuid4()), channel=channel_USD)]
+ )
+
+ variables = {"filter": checkouts_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+ content = get_graphql_content(response)
+ checkout_list = content["data"]["checkouts"]["edges"]
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+
+ assert len(checkout_list) == 1
+ assert checkout_list[0]["node"]["id"] == checkout_id
+
+
+QUERY_CHECKOUT_WITH_SORT = """
+ query ($sort_by: CheckoutSortingInput!) {
+ checkouts(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ token
+ }
+ }
+ }
+ }
+"""
+
+
+ "checkout_sort, result_order",
+ [
+ ({"field": "CREATION_DATE", "direction": "ASC"}, [1, 0, 2]),
+ ({"field": "CREATION_DATE", "direction": "DESC"}, [2, 0, 1]),
+ ({"field": "CUSTOMER", "direction": "ASC"}, [2, 0, 1]),
+ ({"field": "CUSTOMER", "direction": "DESC"}, [1, 0, 2]),
+ ({"field": "PAYMENT", "direction": "ASC"}, [0, 1, 2]),
+ ({"field": "PAYMENT", "direction": "DESC"}, [2, 1, 0]),
+ ],
+)
+def test_query_checkout_with_sort(
+ checkout_sort,
+ result_order,
+ staff_api_client,
+ permission_manage_checkouts,
+ address,
+ channel_USD,
+):
+ created_checkouts = []
+ with freeze_time("2017-01-14"):
+ created_checkouts.append(
+ Checkout.objects.create(
+ token=str(uuid.uuid4()),
+ billing_address=address,
+ channel=channel_USD,
+ )
+ )
+ with freeze_time("2012-01-14"):
+ address2 = address.get_copy()
+ address2.first_name = "Walter"
+ address2.save()
+ created_checkouts.append(
+ Checkout.objects.create(
+ token=str(uuid.uuid4()),
+ billing_address=address2,
+ channel=channel_USD,
+ )
+ )
+ address3 = address.get_copy()
+ address3.last_name = "Alice"
+ address3.save()
+ created_checkouts.append(
+ Checkout.objects.create(
+ token=str(uuid.uuid4()),
+ billing_address=address3,
+ channel=channel_USD,
+ )
+ )
+
+ Payment.objects.create(
+ checkout=created_checkouts[0], charge_status=ChargeStatus.FULLY_CHARGED
+ )
+
+ Payment.objects.create(
+ checkout=created_checkouts[1], charge_status=ChargeStatus.NOT_CHARGED
+ )
+
+ variables = {"sort_by": checkout_sort}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(QUERY_CHECKOUT_WITH_SORT, variables)
+ content = get_graphql_content(response)
+ checkouts = content["data"]["checkouts"]["edges"]
+
+ for checkout, checkout_number in enumerate(result_order):
+ assert checkouts[checkout]["node"]["token"] == str(
+ created_checkouts[checkout_number].pk
+ )
+
+
+ "checkouts_filter, count",
+ [
+ ({"search": "user_email"}, 2),
+ ({"search": "[email protected]"}, 1),
+ ({"search": "Leslie"}, 1),
+ ({"search": "Wade"}, 1),
+ ({"search": ""}, 4),
+ ({"search": "ExternalID"}, 1),
+ ],
+)
+def test_checkouts_query_with_filter_search(
+ checkouts_filter,
+ count,
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ customer_user,
+ channel_USD,
+):
+
+ user1 = User.objects.create(email="[email protected]")
+ user2 = User.objects.create(email="[email protected]")
+ user3 = User.objects.create(email="[email protected]")
+
+ checkouts = Checkout.objects.bulk_create(
+ [
+ Checkout(
+ user=customer_user,
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
+ ),
+ Checkout(
+ token=str(uuid.uuid4()),
+ user=user1,
+ channel=channel_USD,
+ ),
+ Checkout(
+ token=str(uuid.uuid4()),
+ user=user2,
+ channel=channel_USD,
+ ),
+ Checkout(
+ token=str(uuid.uuid4()),
+ user=user3,
+ channel=channel_USD,
+ ),
+ ]
+ )
+
+ checkout_with_payment = checkouts[1]
+ payment = Payment.objects.create(
+ checkout=checkout_with_payment, psp_reference="ExternalID"
+ )
+ payment.transactions.create(gateway_response={}, is_success=True)
+ variables = {"filter": checkouts_filter}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+ content = get_graphql_content(response)
+
+ print(content)
+ assert content["data"]["checkouts"]["totalCount"] == count
+
+
+def test_checkouts_query_with_filter_search_by_global_payment_id(
+ checkout_query_with_filter,
+ staff_api_client,
+ permission_manage_checkouts,
+ customer_user,
+ channel_USD,
+):
+
+ checkouts = Checkout.objects.bulk_create(
+ [
+ Checkout(
+ user=customer_user,
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
+ ),
+ Checkout(
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
+ user=User.objects.create(email="[email protected]"),
+ ),
+ ]
+ )
+
+ checkout_with_payment = checkouts[0]
+ payment = Payment.objects.create(checkout=checkout_with_payment)
+ global_id = graphene.Node.to_global_id("Payment", payment.pk)
+
+ variables = {"filter": {"search": global_id}}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["checkouts"]["totalCount"] == 1
+
+
+def test_checkouts_query_with_filter_search_by_token(
+ checkout_query_with_filter, checkout, staff_api_client, permission_manage_checkouts
+):
+ variables = {"filter": {"search": checkout.pk}}
+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)
+ response = staff_api_client.post_graphql(checkout_query_with_filter, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["checkouts"]["totalCount"] == 1
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 08f9745578..974f902bae 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1139,6 +1139,14 @@ enum CheckoutErrorCode {
UNAVAILABLE_VARIANT_IN_CHANNEL
}
+input CheckoutFilterInput {
+ customer: String
+ created: DateRangeInput
+ search: String
+ metadata: [MetadataFilter]
+ channels: [ID]
+}
+
type CheckoutLanguageCodeUpdate {
checkout: Checkout
checkoutErrors: [CheckoutError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
@@ -1212,6 +1220,17 @@ type CheckoutShippingMethodUpdate {
errors: [CheckoutError!]!
}
+enum CheckoutSortField {
+ CREATION_DATE
+ CUSTOMER
+ PAYMENT
+}
+
+input CheckoutSortingInput {
+ direction: OrderDirection!
+ field: CheckoutSortField!
+}
+
type ChoiceValue {
raw: String
verbose: String
@@ -5896,7 +5915,7 @@ type Query {
exportFiles(filter: ExportFileFilterInput, sortBy: ExportFileSortingInput, before: String, after: String, first: Int, last: Int): ExportFileCountableConnection
taxTypes: [TaxType]
checkout(token: UUID): Checkout
- checkouts(channel: String, before: String, after: String, first: Int, last: Int): CheckoutCountableConnection
+ checkouts(sortBy: CheckoutSortingInput, filter: CheckoutFilterInput, channel: String, before: String, after: String, first: Int, last: Int): CheckoutCountableConnection
checkoutLines(before: String, after: String, first: Int, last: Int): CheckoutLineCountableConnection
channel(id: ID): Channel
channels: [Channel!]