Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `search` to giftcard query (#13173)
Piotr Zabieglikf00b8f27b53d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 31b594ce9d..bea4ecbd81 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,6 +65,7 @@ All notable, unreleased changes to this project will be documented in this file.- Added `GiftCardFilterInput.createdByEmail` filter - #13132 by @Smit-Parmar- Remove `Preview feature` label from `metafield`, `metafields`, `metadata`,`privateMetafield`, `privateMetafields` and `privateMetadata` fields - #13245 by @korycins+- Add `search` to `giftCards` query - #13173 by @zedzior### Saleor Appsdiff --git a/saleor/giftcard/migrations/0019_auto_20230626_1315.py b/saleor/giftcard/migrations/0019_auto_20230626_1315.pynew file mode 100644index 0000000000..b4dc5534e7--- /dev/null+++ b/saleor/giftcard/migrations/0019_auto_20230626_1315.py@@ -0,0 +1,34 @@+# Generated by Django 3.2.18 on 2023-06-26 13:15++import django.contrib.postgres.indexes+import django.contrib.postgres.search+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("giftcard", "0018_metadata_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="giftcard",+ name="search_index_dirty",+ field=models.BooleanField(default=True),+ ),+ migrations.AddField(+ model_name="giftcard",+ name="search_vector",+ field=django.contrib.postgres.search.SearchVectorField(+ blank=True, null=True+ ),+ ),+ migrations.RunSQL(+ """+ ALTER TABLE giftcard_giftcard+ ALTER COLUMN search_index_dirty+ SET DEFAULT true;+ """,+ migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/giftcard/migrations/0020_search_vector_index.py b/saleor/giftcard/migrations/0020_search_vector_index.pynew file mode 100644index 0000000000..4f99263d0f--- /dev/null+++ b/saleor/giftcard/migrations/0020_search_vector_index.py@@ -0,0 +1,21 @@+# Generated by Django 3.2.18 on 2023-06-26 13:28++from django.contrib.postgres.operations import AddIndexConcurrently+import django.contrib.postgres.indexes+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("giftcard", "0019_auto_20230626_1315"),+ ]+ atomic = False+ operations = [+ AddIndexConcurrently(+ model_name="giftcard",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["search_vector"],+ name="giftcard_tsearch",+ ),+ ),+ ]diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.pyindex e55770f499..2ec15f3575 100644--- a/saleor/giftcard/models.py+++ b/saleor/giftcard/models.py@@ -2,6 +2,7 @@ import osfrom django.conf import settingsfrom django.contrib.postgres.indexes import GinIndex+from django.contrib.postgres.search import SearchVectorFieldfrom django.core.validators import MinLengthValidatorfrom django.db import modelsfrom django.db.models import JSONField, Q@@ -110,6 +111,8 @@ class GiftCard(ModelWithMetadata):current_balance = MoneyField(amount_field="current_balance_amount", currency_field="currency")+ search_vector = SearchVectorField(blank=True, null=True)+ search_index_dirty = models.BooleanField(default=True)objects = GiftCardManager()@@ -118,6 +121,8 @@ class GiftCard(ModelWithMetadata):permissions = ((GiftcardPermissions.MANAGE_GIFT_CARD.codename, "Manage gift cards."),)+ indexes = [GinIndex(name="giftcard_tsearch", fields=["search_vector"])]+ indexes.extend(ModelWithMetadata.Meta.indexes)@propertydef display_code(self):diff --git a/saleor/giftcard/search.py b/saleor/giftcard/search.pynew file mode 100644index 0000000000..9b11c099b0--- /dev/null+++ b/saleor/giftcard/search.py@@ -0,0 +1,68 @@+from typing import List, Union++from django.contrib.postgres.search import SearchQuery+from django.db.models import Q, QuerySet, Value, prefetch_related_objects++from ..account.models import User+from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector+from .models import GiftCard++GIFTCARD_FIELDS_TO_PREFETCH = ["used_by", "created_by"]+++def _add_vector(vectors: List[NoValidationSearchVector], field):+ if field:+ vectors += [NoValidationSearchVector(Value(field), config="simple")]+++def prepare_gift_card_search_vector_value(+ gift_card: GiftCard,+) -> List[NoValidationSearchVector]:+ search_vectors = [NoValidationSearchVector(Value(gift_card.code), config="simple")]+ _add_vector(search_vectors, gift_card.used_by_email)+ _add_vector(search_vectors, gift_card.created_by_email)+ if gift_card.used_by:+ _add_vector(search_vectors, gift_card.used_by.email)+ _add_vector(search_vectors, gift_card.used_by.first_name)+ _add_vector(search_vectors, gift_card.used_by.last_name)+ if gift_card.created_by:+ _add_vector(search_vectors, gift_card.created_by.email)+ _add_vector(search_vectors, gift_card.created_by.first_name)+ _add_vector(search_vectors, gift_card.created_by.last_name)++ return search_vectors+++def mark_gift_cards_search_index_as_dirty(gift_cards: Union[List[GiftCard], QuerySet]):+ for gift_card in gift_cards:+ gift_card.search_index_dirty = True+ GiftCard.objects.bulk_update(gift_cards, ["search_index_dirty"])+++def mark_gift_cards_search_index_as_dirty_by_users(users: List[User]):+ emails = [user.email for user in users]+ gift_cards = GiftCard.objects.filter(+ Q(used_by_email__in=emails)+ | Q(created_by_email__in=emails)+ | Q(used_by__in=users)+ | Q(created_by__in=users)+ )+ mark_gift_cards_search_index_as_dirty(gift_cards)+++def update_gift_cards_search_vector(gift_cards: List[GiftCard]):+ prefetch_related_objects(gift_cards, *GIFTCARD_FIELDS_TO_PREFETCH)+ for gift_card in gift_cards:+ gift_card.search_index_dirty = False+ gift_card.search_vector = FlatConcatSearchVector(+ *prepare_gift_card_search_vector_value(gift_card)+ )++ GiftCard.objects.bulk_update(gift_cards, ["search_vector", "search_index_dirty"])+++def search_gift_cards(qs, value):+ if value:+ query = SearchQuery(value, search_type="websearch", config="simple")+ qs = qs.filter(search_vector=query)+ return qsdiff --git a/saleor/giftcard/tasks.py b/saleor/giftcard/tasks.pyindex 7356b519aa..f148379331 100644--- a/saleor/giftcard/tasks.py+++ b/saleor/giftcard/tasks.py@@ -1,11 +1,14 @@from celery.utils.log import get_task_logger+from django.conf import settingsfrom django.utils import timezonefrom ..celeryconf import appfrom .events import gift_cards_deactivated_eventfrom .models import GiftCard+from .search import update_gift_cards_search_vectortask_logger = get_task_logger(__name__)+GIFT_CARD_BATCH_SIZE = 300@app.task@@ -18,3 +21,16 @@ def deactivate_expired_cards_task():count = gift_cards.update(is_active=False)gift_cards_deactivated_event(gift_card_ids, user=None, app=None)task_logger.debug("Deactivate %s gift cards", count)+++ queue=settings.UPDATE_SEARCH_VECTOR_INDEX_QUEUE_NAME,+ expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,+)+def update_gift_cards_search_vector_task():+ gift_cards = GiftCard.objects.filter(search_index_dirty=True)+ if not gift_cards:+ return+ gift_cards_batch = list(gift_cards[:GIFT_CARD_BATCH_SIZE])+ update_gift_cards_search_vector(gift_cards_batch)+ update_gift_cards_search_vector_task.delay()diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex f360830ff6..c29aae7767 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -270,3 +270,14 @@ def is_gift_card_expired(gift_card: GiftCard):"""Return True when gift card expiry date pass."""today = timezone.now().date()return bool(gift_card.expiry_date) and gift_card.expiry_date < today # type: ignore+++def get_user_gift_cards(user: "User") -> "QuerySet":+ from django.db.models import Q++ return GiftCard.objects.filter(+ Q(used_by_email=user.email)+ | Q(created_by_email=user.email)+ | Q(used_by=user)+ | Q(created_by=user)+ )diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.pyindex 7ad7a7463a..f6ca327756 100644--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py@@ -12,6 +12,7 @@ from ....account.events import CustomerEventsfrom ....account.search import prepare_user_search_document_valuefrom ....checkout import AddressTypefrom ....core.tracing import traced_atomic_transaction+from ....giftcard.search import mark_gift_cards_search_index_as_dirty_by_usersfrom ....giftcard.utils import assign_user_gift_cardsfrom ....order.utils import match_orders_with_new_userfrom ....permission.enums import AccountPermissions@@ -551,7 +552,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):customer_events = []app = get_app_promise(info.context).get()staff_user = info.context.user-+ users_with_name_or_email_updated = []for updated_instance, old_instance in zip(instances, old_instances):cls.call_event(manager.customer_updated, updated_instance)new_email = updated_instance.email@@ -577,6 +578,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):)assign_user_gift_cards(updated_instance)match_orders_with_new_user(updated_instance)+ users_with_name_or_email_updated.append(updated_instance)if has_new_name:customer_events.append(@@ -588,6 +590,8 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):parameters={"message": new_fullname},))+ users_with_name_or_email_updated.append(updated_instance)+if was_activated:customer_events.append(models.CustomerEvent(@@ -611,6 +615,7 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):cls.call_event(manager.customer_metadata_updated, updated_instance)models.CustomerEvent.objects.bulk_create(customer_events)+ mark_gift_cards_search_index_as_dirty_by_users(users_with_name_or_email_updated)@classmethoddef get_results(cls, instances_data_with_errors_list, reject_everything=False):diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 525602df71..c73ea56e23 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -12,6 +12,8 @@ from ....checkout import AddressTypefrom ....core.exceptions import PermissionDeniedfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils.url import validate_storefront_url+from ....giftcard.search import mark_gift_cards_search_index_as_dirty+from ....giftcard.utils import get_user_gift_cardsfrom ....graphql.utils import get_user_or_app_from_contextfrom ....permission.auth_filters import AuthorizationFiltersfrom ....permission.enums import AccountPermissions@@ -339,6 +341,10 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.customer_metadata_updated, instance)+ if cleaned_input.get("first_name") or cleaned_input.get("last_name"):+ if user_gift_cards := get_user_gift_cards(instance):+ mark_gift_cards_search_index_as_dirty(user_gift_cards)+class UserDeleteMixin:class Meta:diff --git a/saleor/graphql/account/mutations/staff/customer_update.py b/saleor/graphql/account/mutations/staff/customer_update.pyindex ddca1b32dc..a9ecb50570 100644--- a/saleor/graphql/account/mutations/staff/customer_update.py+++ b/saleor/graphql/account/mutations/staff/customer_update.py@@ -1,10 +1,12 @@from copy import copyimport graphene+from django.db.models import QuerySetfrom .....account import events as account_eventsfrom .....account import models-from .....giftcard.utils import assign_user_gift_cards+from .....giftcard.search import mark_gift_cards_search_index_as_dirty+from .....giftcard.utils import assign_user_gift_cards, get_user_gift_cardsfrom .....order.utils import match_orders_with_new_userfrom .....permission.enums import AccountPermissionsfrom .....webhook.event_types import WebhookEventAsyncType@@ -94,6 +96,20 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):account_id=old_instance.id,)+ @classmethod+ def update_gift_card_search_vector(+ cls,+ old_instance: models.User,+ new_instance: models.User,+ gift_cards: QuerySet,+ ):+ new_email = new_instance.email+ new_fullname = new_instance.get_full_name()+ has_new_name = old_instance.get_full_name() != new_fullname+ has_new_email = old_instance.email != new_email+ if has_new_email or has_new_name:+ mark_gift_cards_search_index_as_dirty(gift_cards)+@classmethoddef perform_mutation(cls, _root, info: ResolveInfo, /, **data):"""Generate events by comparing the old instance with the new data.@@ -127,5 +143,10 @@ class CustomerUpdate(CustomerCreate, ModelWithExtRefMutation):manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.customer_metadata_updated, new_instance)+ if gift_cards := get_user_gift_cards(new_instance):+ cls.update_gift_card_search_vector(+ original_instance, new_instance, gift_cards+ )+# Return the responsereturn cls.success_response(new_instance)diff --git a/saleor/graphql/account/mutations/staff/staff_update.py b/saleor/graphql/account/mutations/staff/staff_update.pyindex 77fa84058d..d000a86e13 100644--- a/saleor/graphql/account/mutations/staff/staff_update.py+++ b/saleor/graphql/account/mutations/staff/staff_update.py@@ -6,7 +6,8 @@ from django.core.exceptions import ValidationErrorfrom .....account import modelsfrom .....account.error_codes import AccountErrorCodefrom .....core.tracing import traced_atomic_transaction-from .....giftcard.utils import assign_user_gift_cards+from .....giftcard.search import mark_gift_cards_search_index_as_dirty+from .....giftcard.utils import assign_user_gift_cards, get_user_gift_cardsfrom .....order.utils import match_orders_with_new_userfrom .....permission.enums import AccountPermissionsfrom .....webhook.event_types import WebhookEventAsyncType@@ -179,13 +180,20 @@ class StaffUpdate(StaffCreate):@classmethoddef perform_mutation(cls, root, info: ResolveInfo, /, **data):- instance, _ = cls.get_instance(info, **data)- old_email = instance.email+ original_instance, _ = cls.get_instance(info, **data)response = super().perform_mutation(root, info, **data)user = response.user- if user.email != old_email:+ has_new_email = user.email != original_instance.email+ has_new_name = original_instance.get_full_name() != user.get_full_name()++ if has_new_email:assign_user_gift_cards(user)match_orders_with_new_user(user)++ if has_new_email or has_new_name:+ if gift_cards := get_user_gift_cards(user):+ mark_gift_cards_search_index_as_dirty(gift_cards)+return response@classmethoddiff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.pyindex e68e8e29eb..7143bde9aa 100644--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py@@ -6,6 +6,8 @@ from .....account import modelsfrom .....account.error_codes import CustomerBulkUpdateErrorCodefrom .....account.events import CustomerEventsfrom .....account.search import generate_address_search_document_value+from .....giftcard.models import GiftCard+from .....giftcard.search import update_gift_cards_search_vectorfrom ....core.enums import ErrorPolicyEnumfrom ....tests.utils import get_graphql_contentfrom ..utils import convert_dict_keys_to_camel_case@@ -779,3 +781,64 @@ def test_customers_bulk_update_metadata_empty_key_in_one_input(== private_metadata_2["value"])mocked_customer_metadata_updated.called_once_with(customer_2)+++def test_customers_bulk_update_trigger_gift_card_search_vector_update(+ staff_api_client,+ customer_users,+ permission_manage_users,+ gift_card_list,+):+ # given+ customer_1 = customer_users[0]+ customer_2 = customer_users[1]++ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)++ customer_1_new_name = "NewName1"+ customer_2_new_name = "NewName2"++ gift_card_1, gift_card_2, gift_card_3 = gift_card_list+ gift_card_1.created_by = customer_1+ gift_card_2.used_by = customer_2+ gift_card_3.used_by_email = customer_1.email+ GiftCard.objects.bulk_update(+ gift_card_list, ["created_by", "used_by", "used_by_email"]+ )++ update_gift_cards_search_vector(gift_card_list)+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is False++ customers_input = [+ {+ "id": customer_1_id,+ "input": {+ "firstName": customer_1_new_name,+ },+ },+ {+ "id": customer_2_id,+ "input": {+ "firstName": customer_2_new_name,+ },+ },+ ]++ variables = {"customers": customers_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_users)+ response = staff_api_client.post_graphql(CUSTOMER_BULK_UPDATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["customerBulkUpdate"]+ assert not data["results"][0]["errors"]+ assert not data["results"][1]["errors"]+ assert data["count"] == 2+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is Truediff --git a/saleor/graphql/account/tests/mutations/account/test_account_update.py b/saleor/graphql/account/tests/mutations/account/test_account_update.pyindex 43be5bbede..d3503f0349 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_update.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_update.py@@ -3,6 +3,7 @@ from unittest.mock import patchfrom ......account.error_codes import AccountErrorCodefrom ......account.models import Userfrom ......checkout import AddressType+from ......giftcard.search import update_gift_cards_search_vectorfrom .....tests.utils import assert_no_permission, get_graphql_contentACCOUNT_UPDATE_QUERY = """@@ -177,3 +178,30 @@ def test_logged_customer_updates_metadata(assert not data["errors"]assert metadata in data["user"]["metadata"]mocked_customer_metadata_updated.assert_called_once_with(user_api_client.user)+++def test_logged_customer_update_names_trigger_gift_card_search_vector_update(+ user_api_client, gift_card, gift_card_used, gift_card_expiry_date+):+ # given+ first_name = "first"+ last_name = "last"+ gift_cards = [gift_card, gift_card_used, gift_card_expiry_date]++ update_gift_cards_search_vector(gift_cards)+ for card in gift_cards:+ card.refresh_from_db()+ assert card.search_index_dirty is False++ variables = {"firstName": first_name, "lastName": last_name}++ # when+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["accountUpdate"]+ assert not data["errors"]+ for card in gift_cards:+ card.refresh_from_db()+ assert card.search_index_dirty is Truediff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py b/saleor/graphql/account/tests/mutations/staff/test_customer_update.pyindex b50d78ceec..8ea2101a50 100644--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py@@ -5,6 +5,8 @@ import graphenefrom ......account import events as account_eventsfrom ......account.error_codes import AccountErrorCodefrom ......account.search import generate_address_search_document_value+from ......giftcard.models import GiftCard+from ......giftcard.search import update_gift_cards_search_vectorfrom .....tests.utils import get_graphql_contentfrom ....tests.utils import convert_dict_keys_to_camel_case@@ -527,3 +529,48 @@ def test_customer_update_assign_gift_cards_and_orders(assert gift_card.created_by_email == customer_user.emailorder.refresh_from_db()assert order.user == customer_user+++def test_customer_update_trigger_gift_card_search_vector_update(+ staff_api_client,+ customer_user,+ gift_card_list,+ permission_manage_users,+):+ # given+ query = UPDATE_CUSTOMER_EMAIL_MUTATION++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ new_email = "[email protected]"++ gift_card_1, gift_card_2, gift_card_3 = gift_card_list+ gift_card_1.created_by = customer_user+ gift_card_2.used_by = customer_user+ gift_card_3.used_by_email = new_email+ GiftCard.objects.bulk_update(+ gift_card_list, ["created_by", "used_by", "used_by_email"]+ )++ update_gift_cards_search_vector(gift_card_list)+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is False++ variables = {+ "id": user_id,+ "email": new_email,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert customer_user.email == new_email+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is Truediff --git a/saleor/graphql/account/tests/mutations/staff/test_staff_update.py b/saleor/graphql/account/tests/mutations/staff/test_staff_update.pyindex 795cbccc29..21ab1bdc27 100644--- a/saleor/graphql/account/tests/mutations/staff/test_staff_update.py+++ b/saleor/graphql/account/tests/mutations/staff/test_staff_update.py@@ -10,6 +10,8 @@ from freezegun import freeze_timefrom ......account.error_codes import AccountErrorCodefrom ......account.models import Group, Userfrom ......core.utils.json_serializer import CustomJsonEncoder+from ......giftcard.models import GiftCard+from ......giftcard.search import update_gift_cards_search_vectorfrom ......permission.enums import AccountPermissionsfrom ......webhook.event_types import WebhookEventAsyncTypefrom ......webhook.payloads import generate_meta, generate_requestor@@ -620,3 +622,42 @@ def test_staff_update_update_email_assign_gift_cards_and_orders(assert gift_card.created_by_email == staff_user.emailorder.refresh_from_db()assert order.user == staff_user+++def test_staff_update_trigger_gift_card_search_vector_update(+ staff_api_client, permission_manage_staff, gift_card_list+):+ # given+ query = STAFF_UPDATE_MUTATIONS+ new_email = "[email protected]"+ user = staff_api_client.user++ id = graphene.Node.to_global_id("User", user.id)+ variables = {"id": id, "input": {"email": new_email}}++ gift_card_1, gift_card_2, gift_card_3 = gift_card_list+ gift_card_1.created_by = user+ gift_card_2.used_by = user+ gift_card_3.created_by_email = new_email+ GiftCard.objects.bulk_update(+ gift_card_list, ["created_by", "used_by", "created_by_email"]+ )++ update_gift_cards_search_vector(gift_card_list)+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is False++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_staff]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["staffUpdate"]["errors"]+ user.refresh_from_db()+ assert user.email == new_email+ for card in gift_card_list:+ card.refresh_from_db()+ assert card.search_index_dirty is Truediff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.pyindex af42454459..5cf48df26c 100644--- a/saleor/graphql/giftcard/schema.py+++ b/saleor/graphql/giftcard/schema.py@@ -2,10 +2,11 @@ import graphenefrom graphql.error import GraphQLErrorfrom ...giftcard import models+from ...giftcard.search import search_gift_cardsfrom ...permission.enums import GiftcardPermissionsfrom ..core import ResolveInfofrom ..core.connection import create_connection_slice, filter_connection_queryset-from ..core.descriptions import ADDED_IN_31+from ..core.descriptions import ADDED_IN_31, ADDED_IN_315, PREVIEW_FEATUREfrom ..core.doc_category import DOC_CATEGORY_GIFT_CARDSfrom ..core.fields import FilterConnectionField, PermissionsFieldfrom ..core.types import NonNullList@@ -49,6 +50,12 @@ class GiftCardQueries(graphene.ObjectType):filter=GiftCardFilterInput(description=("Filtering options for gift cards." + ADDED_IN_31)),+ search=graphene.String(+ description="Search gift cards by email and name of user, "+ "who created or used the gift card, and by code."+ + ADDED_IN_315+ + PREVIEW_FEATURE+ ),description="List of gift cards.",permissions=[GiftcardPermissions.MANAGE_GIFT_CARD,@@ -83,7 +90,7 @@ class GiftCardQueries(graphene.ObjectType):@staticmethoddef resolve_gift_cards(- _root, info: ResolveInfo, /, *, sort_by=None, filter=None, **kwargs+ _root, info: ResolveInfo, /, *, sort_by=None, filter=None, search=None, **kwargs):sorting_by_balance = sort_by and "current_balance_amount" in sort_by.get("field", []@@ -92,6 +99,8 @@ class GiftCardQueries(graphene.ObjectType):if sorting_by_balance and not filtering_by_currency:raise GraphQLError("Sorting by balance requires filtering by currency.")qs = resolve_gift_cards()+ if search:+ qs = search_gift_cards(qs, search)qs = filter_connection_queryset(qs, {"sort_by": sort_by, "filter": filter, **kwargs})diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_search.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_search.pynew file mode 100644index 0000000000..3ff74f4a69--- /dev/null+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_search.py@@ -0,0 +1,55 @@+import pytest++from saleor.giftcard.search import update_gift_cards_search_vector++from ....tests.utils import get_graphql_content++QUERY_GIFT_CARDS = """+ query giftCards(+ $sortBy: GiftCardSortingInput,+ $filter: GiftCardFilterInput,+ $search: String,+ ){+ giftCards(first: 10, filter: $filter, sortBy: $sortBy, search: $search) {+ edges {+ node {+ id+ code+ }+ }+ totalCount+ }+ }+"""+++ "search,indexes",+ [("expiry", [0, 1]), ("[email protected]", [2]), ("banana", [])],+)+def test_query_gift_cards_with_search(+ search,+ indexes,+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ permission_manage_gift_card,+):+ # given+ gift_card_list = [gift_card, gift_card_expiry_date, gift_card_used]+ update_gift_cards_search_vector(gift_card_list)+ variables = {"search": search}++ # when+ response = staff_api_client.post_graphql(+ QUERY_GIFT_CARDS, variables, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCards"]["edges"]+ assert len(data) == len(indexes)+ assert {card["node"]["code"] for card in data} == {+ gift_card_list[index].code for index in indexes+ }diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex dce496e7f9..6debc3d4c9 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -982,6 +982,15 @@ type Query {"""filter: GiftCardFilterInput+ """+ Search gift cards by email and name of user, who created or used the gift card, and by code.++ Added in Saleor 3.15.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ search: String+"""Return the elements in the list that come before the specified cursor."""before: Stringdiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex fa49b5989a..6df0291164 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -24,6 +24,7 @@ from ..discount.utils import ()from ..giftcard import events as gift_card_eventsfrom ..giftcard.models import GiftCard+from ..giftcard.search import mark_gift_cards_search_index_as_dirtyfrom ..payment.model_helpers import get_total_authorizedfrom ..product.utils.digital_products import get_default_digital_content_settingsfrom ..shipping.interface import ShippingMethodData@@ -448,6 +449,7 @@ def set_gift_card_user(else User.objects.filter(email=used_by_email).first())gift_card.used_by_email = used_by_email+ mark_gift_cards_search_index_as_dirty([gift_card])def _update_allocations_for_line(diff --git a/saleor/settings.py b/saleor/settings.pyindex e54f36486e..8a41380525 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -598,6 +598,11 @@ CELERY_BEAT_SCHEDULE = {"schedule": timedelta(seconds=20),"options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},},+ "update-gift-cards-search-vectors": {+ "task": "saleor.giftcard.tasks.update_gift_cards_search_vector_task",+ "schedule": timedelta(seconds=20),+ "options": {"expires": BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC},+ },"expire-orders": {"task": "saleor.order.tasks.expire_orders_task","schedule": BEAT_EXPIRE_ORDERS_AFTER_TIMEDELTA,