Skip to content

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

Revert gift card tags query (#8409)

Marcin Gębalaa568d427d68c
diff --git a/saleor/giftcard/__init__.py b/saleor/giftcard/__init__.py
index e451819c87..00af1441ce 100644
--- a/saleor/giftcard/__init__.py
+++ b/saleor/giftcard/__init__.py
@@ -16,7 +16,7 @@ class GiftCardEvents:
DEACTIVATED = "deactivated"
BALANCE_RESET = "balance_reset"
EXPIRY_DATE_UPDATED = "expiry_date_updated"
- TAGS_UPDATED = "tags_updated"
+ TAG_UPDATED = "tag_updated"
SENT_TO_CUSTOMER = "sent_to_customer"
RESENT = "resent"
NOTE_ADDED = "note_added"
@@ -30,7 +30,7 @@ class GiftCardEvents:
(DEACTIVATED, "The gift card was deactivated."),
(BALANCE_RESET, "The gift card balance was reset."),
(EXPIRY_DATE_UPDATED, "The gift card expiry date was updated."),
- (TAGS_UPDATED, "The gift card tags were updated."),
+ (TAG_UPDATED, "The gift card tag was updated."),
(SENT_TO_CUSTOMER, "The gift card was sent to the customer."),
(RESENT, "The gift card was resent to the customer."),
(NOTE_ADDED, "A note was added to the gift card."),
diff --git a/saleor/giftcard/error_codes.py b/saleor/giftcard/error_codes.py
index 1415313be6..c81ddbe3cd 100644
--- a/saleor/giftcard/error_codes.py
+++ b/saleor/giftcard/error_codes.py
@@ -8,4 +8,3 @@ class GiftCardErrorCode(Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
- DUPLICATED_INPUT_ITEM = "duplicated_input_item"
diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.py
index ed2b123900..dfff1dfe7b 100644
--- a/saleor/giftcard/events.py
+++ b/saleor/giftcard/events.py
@@ -1,4 +1,4 @@
-from typing import Iterable, List, Optional, Tuple
+from typing import Iterable, Optional, Tuple
from ..account.models import User
from ..app.models import App
@@ -100,9 +100,9 @@ def gift_card_expiry_date_updated_event(
)
-def gift_card_tags_updated_event(
+def gift_card_tag_updated_event(
gift_card: GiftCard,
- old_tags: List[str],
+ old_gift_card: GiftCard,
user: UserType,
app: AppType,
):
@@ -112,12 +112,10 @@ def gift_card_tags_updated_event(
gift_card=gift_card,
user=user,
app=app,
- type=GiftCardEvents.TAGS_UPDATED,
+ type=GiftCardEvents.TAG_UPDATED,
parameters={
- "tags": list(
- gift_card.tags.order_by("name").values_list("name", flat=True)
- ),
- "old_tags": old_tags,
+ "tag": gift_card.tag,
+ "old_tag": old_gift_card.tag,
},
)
diff --git a/saleor/giftcard/migrations/0010_auto_20211007_0546.py b/saleor/giftcard/migrations/0010_auto_20211007_0546.py
deleted file mode 100644
index 62e1f057fb..0000000000
--- a/saleor/giftcard/migrations/0010_auto_20211007_0546.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# Generated by Django 3.2.6 on 2021-10-07 05:46
-
-import django.contrib.postgres.indexes
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- ("giftcard", "0009_giftcard_fulfillment_line"),
- ]
-
- operations = [
- migrations.CreateModel(
- name="GiftCardTag",
- fields=[
- (
- "id",
- models.AutoField(
- auto_created=True,
- primary_key=True,
- serialize=False,
- verbose_name="ID",
- ),
- ),
- ("name", models.CharField(max_length=255, unique=True)),
- ],
- options={"ordering": ("name",)},
- ),
- migrations.RemoveIndex(
- model_name="giftcard",
- name="giftcard_p_meta_idx",
- ),
- migrations.RemoveIndex(
- model_name="giftcard",
- name="giftcard_meta_idx",
- ),
- migrations.RemoveIndex(
- model_name="giftcard",
- name="giftcard_search_gin",
- ),
- migrations.AddField(
- model_name="giftcard",
- name="tags",
- field=models.ManyToManyField(
- related_name="gift_cards", to="giftcard.GiftCardTag"
- ),
- ),
- migrations.AddIndex(
- model_name="giftcardtag",
- index=django.contrib.postgres.indexes.GinIndex(
- fields=["name"],
- name="gift_card_tag_search_gin",
- opclasses=["gin_trgm_ops"],
- ),
- ),
- ]
diff --git a/saleor/giftcard/migrations/0011_auto_20211007_0547.py b/saleor/giftcard/migrations/0011_auto_20211007_0547.py
deleted file mode 100644
index 84ea1efba0..0000000000
--- a/saleor/giftcard/migrations/0011_auto_20211007_0547.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# Generated by Django 3.2.6 on 2021-10-07 05:47
-
-from django.db import migrations
-
-
-def move_gift_card_tags_to_objects(apps, schema_editor):
- GiftCard = apps.get_model("giftcard", "GiftCard")
- GiftCardTag = apps.get_model("giftcard", "GiftCardTag")
- for card in GiftCard.objects.iterator():
- if card.tag:
- tag, _created = GiftCardTag.objects.get_or_create(name=card.tag)
- card.tags.add(tag)
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- ("giftcard", "0010_auto_20211007_0546"),
- ]
-
- operations = [
- migrations.RunPython(move_gift_card_tags_to_objects, migrations.RunPython.noop),
- ]
diff --git a/saleor/giftcard/migrations/0012_auto_20211007_0655.py b/saleor/giftcard/migrations/0012_auto_20211007_0655.py
deleted file mode 100644
index 4433ff3631..0000000000
--- a/saleor/giftcard/migrations/0012_auto_20211007_0655.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Generated by Django 3.2.6 on 2021-10-07 06:55
-
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- ("giftcard", "0011_auto_20211007_0547"),
- ]
-
- operations = [
- migrations.RemoveField(
- model_name="giftcard",
- name="tag",
- ),
- migrations.AlterField(
- model_name="giftcardevent",
- name="type",
- field=models.CharField(
- choices=[
- ("issued", "The gift card was created be staff user or app."),
- ("bought", "The gift card was bought by customer."),
- ("updated", "The gift card was updated."),
- ("activated", "The gift card was activated."),
- ("deactivated", "The gift card was deactivated."),
- ("balance_reset", "The gift card balance was reset."),
- ("expiry_date_updated", "The gift card expiry date was updated."),
- ("tags_updated", "The gift card tags were updated."),
- ("sent_to_customer", "The gift card was sent to the customer."),
- ("resent", "The gift card was resent to the customer."),
- ("note_added", "A note was added to the gift card."),
- ("used_in_order", "The gift card was used in order."),
- ],
- max_length=255,
- ),
- ),
- ]
diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.py
index 878cad1015..9b733a0135 100644
--- a/saleor/giftcard/models.py
+++ b/saleor/giftcard/models.py
@@ -14,21 +14,6 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from . import GiftCardEvents
-class GiftCardTag(models.Model):
- name = models.CharField(max_length=255, unique=True)
-
- class Meta:
- ordering = ("name",)
- indexes = [
- GinIndex(
- name="gift_card_tag_search_gin",
- # `opclasses` and `fields` should be the same length
- fields=["name"],
- opclasses=["gin_trgm_ops"],
- ),
- ]
-
-
class GiftCardQueryset(models.QuerySet):
def active(self, date):
return self.filter(
@@ -66,7 +51,7 @@ class GiftCard(ModelWithMetadata):
expiry_date = models.DateField(null=True, blank=True)
- tags = models.ManyToManyField(GiftCardTag, "gift_cards")
+ tag = models.CharField(max_length=255, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
last_used_on = models.DateTimeField(null=True, blank=True)
product = models.ForeignKey(
@@ -112,6 +97,15 @@ class GiftCard(ModelWithMetadata):
permissions = (
(GiftcardPermissions.MANAGE_GIFT_CARD.codename, "Manage gift cards."),
)
+ indexes = [
+ *ModelWithMetadata.Meta.indexes,
+ GinIndex(
+ name="giftcard_search_gin",
+ # `opclasses` and `fields` should be the same length
+ fields=["tag"],
+ opclasses=["gin_trgm_ops"],
+ ),
+ ]
@property
def display_code(self):
diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.py
index 2bb3dbca63..3d9c880f58 100644
--- a/saleor/graphql/channel/mutations.py
+++ b/saleor/graphql/channel/mutations.py
@@ -15,7 +15,7 @@ from ..account.enums import CountryCodeEnum
from ..core.descriptions import ADDED_IN_31
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import ChannelError, ChannelErrorCode
-from ..core.utils import get_duplicated_values, get_duplicates_items
+from ..core.utils import get_duplicated_values, get_duplicates_ids
from ..utils.validators import check_for_duplicates
from .types import Channel
@@ -269,7 +269,7 @@ class BaseChannelListingMutation(BaseMutation):
errors: ErrorType,
error_code,
):
- duplicated_ids = get_duplicates_items(add_channels_ids, remove_channels_ids)
+ duplicated_ids = get_duplicates_ids(add_channels_ids, remove_channels_ids)
if duplicated_ids:
error_msg = (
"The same object cannot be in both lists "
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 741721a207..2e06f7b528 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -316,11 +316,6 @@ class PaymentError(Error):
class GiftCardError(Error):
code = GiftCardErrorCode(description="The error code.", required=True)
- tags = graphene.List(
- graphene.NonNull(graphene.String),
- description="List of tag values that cause the error.",
- required=False,
- )
class PluginError(Error):
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 8e24fee864..1bae07f2bf 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -116,7 +116,7 @@ def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):
)
-def get_duplicates_items(first_list, second_list):
+def get_duplicates_ids(first_list, second_list):
"""Return items that appear on both provided lists."""
if first_list and second_list:
return set(first_list) & set(second_list)
diff --git a/saleor/graphql/giftcard/dataloaders.py b/saleor/graphql/giftcard/dataloaders.py
index a57987d5f7..8627552f7c 100644
--- a/saleor/graphql/giftcard/dataloaders.py
+++ b/saleor/graphql/giftcard/dataloaders.py
@@ -1,6 +1,6 @@
from collections import defaultdict
-from ...giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
+from ...giftcard.models import GiftCard, GiftCardEvent
from ..core.dataloaders import DataLoader
@@ -24,22 +24,3 @@ class GiftCardEventsByGiftCardIdLoader(DataLoader):
for event in events.iterator():
events_map[event.gift_card_id].append(event)
return [events_map.get(gift_card_id, []) for gift_card_id in keys]
-
-
-class GiftCardTagsByGiftCardIdLoader(DataLoader):
- context_key = "giftcardtags_by_giftcard"
-
- def batch_load(self, keys):
- gift_card_gift_card_tags = GiftCard.tags.through.objects.filter(
- giftcard_id__in=keys
- )
- tags_ids = [
- gift_card_tag.giftcardtag_id for gift_card_tag in gift_card_gift_card_tags
- ]
- tags = GiftCardTag.objects.in_bulk(tags_ids)
- tags_map = defaultdict(list)
- for gift_card_tag in gift_card_gift_card_tags:
- tags_map[gift_card_tag.giftcard_id].append(
- tags[gift_card_tag.giftcardtag_id]
- )
- return [tags_map.get(gift_card_id, []) for gift_card_id in keys]
diff --git a/saleor/graphql/giftcard/filters.py b/saleor/graphql/giftcard/filters.py
index 5a82229ddb..47636ab8de 100644
--- a/saleor/graphql/giftcard/filters.py
+++ b/saleor/graphql/giftcard/filters.py
@@ -15,6 +15,12 @@ from ..product.types import products as product_types
from ..utils import resolve_global_ids_to_primary_keys
+def filter_gift_card_tag(qs, _, value):
+ if not value:
+ return qs
+ return qs.filter(tag__ilike=value)
+
+
def filter_products(qs, _, value):
if value:
_, product_pks = resolve_global_ids_to_primary_keys(
@@ -44,8 +50,7 @@ def filter_gift_cards_by_used_by_user(qs, user_pks):
def filter_tags_list(qs, _, value):
if not value:
return qs
- tags = models.GiftCardTag.objects.filter(name__in=value)
- return qs.filter(Exists(tags.filter(pk=OuterRef("tags__id"))))
+ return qs.filter(tag__in=value)
def filter_currency(qs, _, value):
@@ -70,6 +75,7 @@ def filter_code(qs, _, value):
class GiftCardFilter(MetadataFilterBase):
+ tag = django_filters.CharFilter(method=filter_gift_card_tag)
tags = ListObjectTypeFilter(input_class=graphene.String, method=filter_tags_list)
products = GlobalIDMultipleChoiceFilter(method=filter_products)
used_by = GlobalIDMultipleChoiceFilter(method=filter_used_by)
@@ -107,18 +113,3 @@ def check_currency_in_filter_data(filter_data: dict):
class GiftCardFilterInput(FilterInputObjectType):
class Meta:
filterset_class = GiftCardFilter
-
-
-def filter_gift_card_tag_search(qs, _, value):
- if not value:
- return qs
- return qs.filter(name__ilike=value)
-
-
-class GiftCardTagFilter(django_filters.FilterSet):
- search = django_filters.CharFilter(method=filter_gift_card_tag_search)
-
-
-class GiftCardTagFilterInput(FilterInputObjectType):
- class Meta:
- filterset_class = GiftCardTagFilter
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index 25ea8e7c7b..b1f0d7af1a 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -1,5 +1,4 @@
from copy import deepcopy
-from typing import Iterable
import graphene
from django.core.exceptions import ValidationError
@@ -7,7 +6,6 @@ from django.core.validators import validate_email
from ...account.models import User
from ...core.permissions import GiftcardPermissions
-from ...core.tracing import traced_atomic_transaction
from ...core.utils.promo_code import generate_promo_code
from ...core.utils.validators import is_date_in_future, user_is_valid
from ...giftcard import events, models
@@ -20,15 +18,11 @@ from ..core.scalars import PositiveDecimal
from ..core.types.common import GiftCardError, PriceInput
from ..core.utils import validate_required_string_field
from ..core.validators import validate_price_precision
-from ..utils.validators import check_for_duplicates
from .types import GiftCard, GiftCardEvent
class GiftCardInput(graphene.InputObjectType):
- add_tags = graphene.List(
- graphene.NonNull(graphene.String),
- description=f"{ADDED_IN_31} The gift card tag.",
- )
+ tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")
expiry_date = graphene.types.datetime.Date(
description=f"{ADDED_IN_31} The gift card expiry date."
)
@@ -76,10 +70,6 @@ class GiftCardCreateInput(GiftCardInput):
class GiftCardUpdateInput(GiftCardInput):
- remove_tags = graphene.List(
- graphene.NonNull(graphene.String),
- description=f"{ADDED_IN_31} The gift card tag.",
- )
balance_amount = PositiveDecimal(
description=f"{ADDED_IN_31} The gift card balance amount.", required=False
)
@@ -216,26 +206,6 @@ class GiftCardCreate(ModelMutation):
resending=False,
)
- @staticmethod
- def assign_gift_card_tags(instance: models.GiftCard, tags_values: Iterable[str]):
- add_tags = {tag.lower() for tag in tags_values}
- add_tags_instances = models.GiftCardTag.objects.filter(name__in=add_tags)
- tags_to_create = add_tags - set(
- add_tags_instances.values_list("name", flat=True)
- )
- models.GiftCardTag.objects.bulk_create(
- [models.GiftCardTag(name=tag) for tag in tags_to_create]
- )
- instance.tags.add(*add_tags_instances)
-
- @classmethod
- @traced_atomic_transaction()
- def _save_m2m(cls, info, instance, cleaned_data):
- super()._save_m2m(info, instance, cleaned_data)
- tags = cleaned_data.get("add_tags")
- if tags:
- cls.assign_gift_card_tags(instance, tags)
-
class GiftCardUpdate(GiftCardCreate):
class Arguments:
@@ -267,13 +237,6 @@ class GiftCardUpdate(GiftCardCreate):
cleaned_input["current_balance_amount"] = amount
cleaned_input["initial_balance_amount"] = amount
- @staticmethod
- def clean_tags(cleaned_input):
- error = check_for_duplicates(cleaned_input, "add_tags", "remove_tags", "tags")
- if error:
- error.code = GiftCardErrorCode.DUPLICATED_INPUT_ITEM.value
- raise ValidationError({"tags": error})
-
@classmethod
def perform_mutation(cls, _root, info, **data):
instance = cls.get_instance(info, **data)
@@ -281,51 +244,25 @@ class GiftCardUpdate(GiftCardCreate):
data = data.get("input")
cleaned_input = cls.clean_input(info, instance, data)
-
- tags_updated = "add_tags" in cleaned_input or "remove_tags" in cleaned_input
- if tags_updated:
- old_tags = list(
- old_instance.tags.order_by("name").values_list("name", flat=True)
- )
-
instance = cls.construct_instance(instance, cleaned_input)
cls.clean_instance(info, instance)
cls.save(info, instance, cleaned_input)
- cls._save_m2m(info, instance, cleaned_input)
- user = info.context.user
- app = info.context.app
if "initial_balance_amount" in cleaned_input:
- events.gift_card_balance_reset_event(instance, old_instance, user, app)
+ events.gift_card_balance_reset_event(
+ instance, old_instance, info.context.user, info.context.app
+ )
if "expiry_date" in cleaned_input:
events.gift_card_expiry_date_updated_event(
- instance, old_instance, user, app
+ instance, old_instance, info.context.user, info.context.app
+ )
+ if "tag" in cleaned_input:
+ events.gift_card_tag_updated_event(
+ instance, old_instance, info.context.user, info.context.app
)
- if tags_updated:
- events.gift_card_tags_updated_event(instance, old_tags, user, app)
return cls.success_response(instance)
- @classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
- cls.clean_tags(cleaned_input)
- return cleaned_input
-
- @classmethod
- @traced_atomic_transaction()
- def _save_m2m(cls, info, instance, cleaned_data):
- super()._save_m2m(info, instance, cleaned_data)
- remove_tags = cleaned_data.get("remove_tags")
- if remove_tags:
- remove_tags = {tag.lower() for tag in remove_tags}
- remove_tags_instances = models.GiftCardTag.objects.filter(
- name__in=remove_tags
- )
- instance.tags.remove(*remove_tags_instances)
- # delete tags without gift card assigned
- remove_tags_instances.filter(gift_cards__isnull=True).delete()
-
class GiftCardDelete(ModelDeleteMutation):
class Arguments:
diff --git a/saleor/graphql/giftcard/resolvers.py b/saleor/graphql/giftcard/resolvers.py
index beeadfcf0b..518e90c0d8 100644
--- a/saleor/graphql/giftcard/resolvers.py
+++ b/saleor/graphql/giftcard/resolvers.py
@@ -7,7 +7,3 @@ def resolve_gift_card(id):
def resolve_gift_cards():
return models.GiftCard.objects.all()
-
-
-def resolve_gift_card_tags():
- return models.GiftCardTag.objects.all()
diff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.py
index a05705582d..41fd050b20 100644
--- a/saleor/graphql/giftcard/schema.py
+++ b/saleor/graphql/giftcard/schema.py
@@ -12,7 +12,7 @@ from .bulk_mutations import (
GiftCardBulkDeactivate,
GiftCardBulkDelete,
)
-from .filters import GiftCardFilterInput, GiftCardTagFilterInput
+from .filters import GiftCardFilterInput
from .mutations import (
GiftCardActivate,
GiftCardAddNote,
@@ -22,9 +22,9 @@ from .mutations import (
GiftCardResend,
GiftCardUpdate,
)
-from .resolvers import resolve_gift_card, resolve_gift_card_tags, resolve_gift_cards
+from .resolvers import resolve_gift_card, resolve_gift_cards
from .sorters import GiftCardSortingInput
-from .types import GiftCard, GiftCardTag
+from .types import GiftCard
class GiftCardQueries(graphene.ObjectType):
@@ -48,13 +48,6 @@ class GiftCardQueries(graphene.ObjectType):
description=f"{ADDED_IN_31} List of gift card currencies.",
required=True,
)
- gift_card_tags = FilterInputConnectionField(
- GiftCardTag,
- filter=GiftCardTagFilterInput(
- description="Filtering options for gift card tags."
- ),
- description="{ADDED_IN_31} List of gift card tags.",
- )
@permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)
def resolve_gift_card(self, info, **data):
@@ -75,10 +68,6 @@ class GiftCardQueries(graphene.ObjectType):
def resolve_gift_card_currencies(self, info, **data):
return set(models.GiftCard.objects.values_list("currency", flat=True))
- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)
- def resolve_gift_card_tags(self, info, **data):
- return resolve_gift_card_tags()
-
class GiftCardMutations(graphene.ObjectType):
gift_card_activate = GiftCardActivate.Field()
diff --git a/saleor/graphql/giftcard/sorters.py b/saleor/graphql/giftcard/sorters.py
index 68e5b831d3..62b7d1438d 100644
--- a/saleor/graphql/giftcard/sorters.py
+++ b/saleor/graphql/giftcard/sorters.py
@@ -4,6 +4,7 @@ from ..core.types import SortInputObjectType
class GiftCardSortField(graphene.Enum):
+ TAG = ["tag"]
PRODUCT = ["product__name", "product__slug"]
USED_BY = ["used_by__first_name", "used_by__last_name", "created"]
CURRENT_BALANCE = ["current_balance_amount", "created"]
diff --git a/saleor/graphql/giftcard/tests/benchmark/fixtures.py b/saleor/graphql/giftcard/tests/benchmark/fixtures.py
index d1b68bc800..90d73a6ceb 100644
--- a/saleor/graphql/giftcard/tests/benchmark/fixtures.py
+++ b/saleor/graphql/giftcard/tests/benchmark/fixtures.py
@@ -4,7 +4,7 @@ import pytest
from prices import Money
from .....giftcard import GiftCardEvents
-from .....giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
+from .....giftcard.models import GiftCard, GiftCardEvent
GIFT_CARD_COUNT_IN_BENCHMARKS = 20
@@ -23,12 +23,11 @@ def gift_cards_for_benchmarks(
created_by_email=customer_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
+ tag="test-tag",
)
for _ in range(GIFT_CARD_COUNT_IN_BENCHMARKS)
]
created_gift_cards = GiftCard.objects.bulk_create(gift_cards)
- tag = GiftCardTag.objects.create(name="benchmark-test-tag")
- tag.gift_cards.add(*created_gift_cards)
parameters = {
"message": "test message",
diff --git a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
index c9e2c73492..8ec0783591 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
@@ -8,23 +8,19 @@ from ....tests.utils import get_graphql_content
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
- $balance: PriceInput!, $userEmail: String, $addTags: [String!],
- $channel: String, $note: String, $expiryDate: Date, $isActive: Boolean!
+ $balance: PriceInput!, $userEmail: String, $tag: String, $channel: String,
+ $note: String, $expiryDate: Date, $isActive: Boolean!
){
giftCardCreate(input: {
- balance: $balance, userEmail: $userEmail, addTags: $addTags,
- channel: $channel, expiryDate: $expiryDate, note: $note,
- isActive: $isActive
- }) {
+ balance: $balance, userEmail: $userEmail, tag: $tag, channel: $channel,
+ expiryDate: $expiryDate, note: $note, isActive: $isActive }) {
giftCard {
id
code
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
initialBalance {
@@ -109,7 +105,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"expiry_date": None,
"isActive": True,
@@ -144,9 +140,7 @@ UPDATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
initialBalance {
@@ -224,14 +218,12 @@ def test_update_gift_card(
# given
initial_balance = 100.0
date_value = date.today() + timedelta(days=365)
- old_tag = gift_card.tags.first()
tag = "new-gift-card-tag"
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "addTags": [tag],
- "removeTags": [old_tag.name],
+ "tag": tag,
"expiryDate": date_value,
},
}
diff --git a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py
index 59a5e5e51b..57fa521fd7 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py
@@ -19,8 +19,8 @@ FRAGMENT_EVENTS = """
email
orderId
orderNumber
- tags
- oldTags
+ tag
+ oldTag
balance {
initialBalance {
amount
@@ -53,9 +53,7 @@ FRAGMENT_GIFT_CARD_DETAILS = (
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
boughtInChannel
@@ -170,7 +168,7 @@ def test_query_gift_cards(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_filter_gift_cards_by_tags(
+def test_filter_gift_cards_by_tag(
staff_api_client,
gift_cards_for_benchmarks,
permission_manage_gift_card,
@@ -195,7 +193,7 @@ def test_filter_gift_cards_by_tags(
content = get_graphql_content(
staff_api_client.post_graphql(
query,
- {"filter": {"tags": ["benchmark-test-tag"]}},
+ {"filter": {"tag": "tag"}},
permissions=[
permission_manage_gift_card,
permission_manage_apps,
diff --git a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
index 82359087ad..b164a16377 100644
--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
@@ -21,9 +21,7 @@ CREATE_GIFT_CARD_MUTATION = """
startDate
endDate
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
initialBalance {
@@ -69,7 +67,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
index 791875dc4a..2a00a5ce84 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -17,9 +17,7 @@ CREATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
initialBalance {
@@ -92,14 +90,11 @@ def test_create_never_expiry_gift_card(
permission_manage_gift_card,
permission_manage_users,
permission_manage_apps,
- gift_card_tag_list,
):
# given
initial_balance = 100
currency = "USD"
- new_tag = "gift-card-tag"
- existing_tag_name = gift_card_tag_list[0].name
- tags = [new_tag, existing_tag_name]
+ tag = "gift-card-tag"
note = "This is gift card note that will be save in gift card event."
variables = {
"input": {
@@ -109,7 +104,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "addTags": tags,
+ "tag": tag,
"note": note,
"isActive": True,
}
@@ -135,8 +130,7 @@ def test_create_never_expiry_gift_card(
assert data["code"]
assert data["displayCode"]
assert not data["expiryDate"]
- assert len(data["tags"]) == 2
- assert {tag["name"] for tag in data["tags"]} == set(tags)
+ assert data["tag"] == tag
assert data["createdBy"]["email"] == staff_api_client.user.email
assert data["createdByEmail"] == staff_api_client.user.email
assert not data["usedBy"]
@@ -197,7 +191,7 @@ def test_create_gift_card_by_app(
"amount": initial_balance,
"currency": currency,
},
- "addTags": [tag],
+ "tag": tag,
"note": note,
"expiryDate": None,
"isActive": False,
@@ -220,8 +214,7 @@ def test_create_gift_card_by_app(
assert data["code"]
assert data["displayCode"]
assert not data["expiryDate"]
- assert len(data["tags"]) == 1
- assert data["tags"][0]["name"] == tag
+ assert data["tag"] == tag
assert not data["createdBy"]
assert not data["createdByEmail"]
assert not data["usedBy"]
@@ -266,7 +259,7 @@ def test_create_gift_card_by_customer(api_client, customer_user, channel_USD):
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"expiryDate": None,
"isActive": True,
@@ -294,7 +287,7 @@ def test_create_gift_card_no_premissions(staff_api_client):
"amount": initial_balance,
"currency": currency,
},
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"expiryDate": None,
"isActive": True,
@@ -329,7 +322,7 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount(
"currency": currency,
},
"userEmail": customer_user.email,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -374,7 +367,7 @@ def test_create_gift_card_with_malformed_email(
"currency": currency,
},
"userEmail": "malformed",
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -421,7 +414,7 @@ def test_create_gift_card_lack_of_channel(
"currency": currency,
},
"userEmail": customer_user.email,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -467,7 +460,7 @@ def test_create_gift_card_with_zero_balance_amount(
"currency": currency,
},
"userEmail": customer_user.email,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -518,7 +511,7 @@ def test_create_gift_card_with_expiry_date(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "addTags": [tag],
+ "tag": tag,
"expiryDate": date_value,
"isActive": True,
}
@@ -591,7 +584,7 @@ def test_create_gift_card_with_expiry_date_type_invalid(
"currency": currency,
},
"userEmail": customer_user.email,
- "addTags": [tag],
+ "tag": tag,
"note": "This is gift card note that will be save in gift card event.",
"expiryDate": date_value,
"isActive": True,
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
index d34cf2cfc0..ce52944213 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
@@ -5,7 +5,6 @@ import pytest
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
-from .....giftcard.models import GiftCardTag
from ....tests.utils import assert_no_permission, get_graphql_content
UPDATE_GIFT_CARD_MUTATION = """
@@ -18,9 +17,7 @@ UPDATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
initialBalance {
@@ -53,8 +50,8 @@ UPDATE_GIFT_CARD_MUTATION = """
app {
name
}
- tags
- oldTags
+ tag
+ oldTag
balance {
initialBalance {
amount
@@ -97,18 +94,17 @@ def test_update_gift_card(
# given
old_initial_balance = float(gift_card.initial_balance.amount)
old_current_balance = float(gift_card.current_balance.amount)
+ old_tag = gift_card.tag
initial_balance = 100.0
currency = gift_card.currency
date_value = date.today() + timedelta(days=365)
- old_tag = gift_card.tags.first().name
- new_tag = "new-gift-card-tag"
- tags_count = GiftCardTag.objects.count()
+ tag = "new-gift-card-tag"
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "addTags": [new_tag],
+ "tag": tag,
"expiryDate": date_value,
},
}
@@ -132,8 +128,7 @@ def test_update_gift_card(
assert not errors
assert data["displayCode"]
assert data["expiryDate"] == date_value.isoformat()
- assert len(data["tags"]) == 2
- assert {tag["name"] for tag in data["tags"]} == {old_tag, new_tag}
+ assert data["tag"] == tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
assert not data["usedBy"]
@@ -172,8 +167,8 @@ def test_update_gift_card(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
},
{
"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
@@ -184,11 +179,11 @@ def test_update_gift_card(
"balance": None,
"expiryDate": date_value.isoformat(),
"oldExpiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
},
{
- "type": GiftCardEvents.TAGS_UPDATED.upper(),
+ "type": GiftCardEvents.TAG_UPDATED.upper(),
"user": {
"email": staff_api_client.user.email,
},
@@ -196,15 +191,13 @@ def test_update_gift_card(
"balance": None,
"expiryDate": None,
"oldExpiryDate": None,
- "tags": [new_tag, old_tag],
- "oldTags": [old_tag],
+ "tag": tag,
+ "oldTag": old_tag,
},
]
for event in data["events"]:
assert event in events
- assert GiftCardTag.objects.count() == tags_count + 1
-
def test_update_gift_card_by_app(
app_api_client,
@@ -212,24 +205,21 @@ def test_update_gift_card_by_app(
permission_manage_gift_card,
permission_manage_users,
permission_manage_apps,
- gift_card_tag_list,
):
# given
old_initial_balance = float(gift_card.initial_balance.amount)
old_current_balance = float(gift_card.current_balance.amount)
- old_tag = gift_card.tags.first()
+ old_tag = gift_card.tag
initial_balance = 100.0
currency = gift_card.currency
date_value = date.today() + timedelta(days=365)
- new_tag = gift_card_tag_list[0].name
- tags_count = GiftCardTag.objects.count()
+ tag = "new-gift-card-tag"
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "addTags": [new_tag],
- "removeTags": [old_tag.name],
+ "tag": tag,
"expiryDate": date_value,
},
}
@@ -253,8 +243,7 @@ def test_update_gift_card_by_app(
assert not errors
assert data["displayCode"]
assert data["expiryDate"] == date_value.isoformat()
- assert len(data["tags"]) == 1
- assert {tag["name"] for tag in data["tags"]} == {new_tag}
+ assert data["tag"] == tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
assert not data["usedBy"]
@@ -291,8 +280,8 @@ def test_update_gift_card_by_app(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
},
{
"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
@@ -301,28 +290,23 @@ def test_update_gift_card_by_app(
"balance": None,
"expiryDate": date_value.isoformat(),
"oldExpiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
},
{
- "type": GiftCardEvents.TAGS_UPDATED.upper(),
+ "type": GiftCardEvents.TAG_UPDATED.upper(),
"user": None,
"app": {"name": app_api_client.app.name},
"balance": None,
"expiryDate": None,
"oldExpiryDate": None,
- "tags": [new_tag],
- "oldTags": [old_tag.name],
+ "tag": tag,
+ "oldTag": old_tag,
},
]
for event in data["events"]:
assert event in events
- with pytest.raises(old_tag._meta.model.DoesNotExist):
- old_tag.refresh_from_db()
-
- assert GiftCardTag.objects.count() == tags_count - 1
-
def test_update_gift_card_by_customer(api_client, customer_user, gift_card):
# given
@@ -332,7 +316,7 @@ def test_update_gift_card_by_customer(api_client, customer_user, gift_card):
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "addTags": [tag],
+ "tag": tag,
},
}
@@ -385,7 +369,7 @@ def test_update_gift_card_balance(
assert not errors
assert not data["expiryDate"]
- assert data["tags"][0]["name"] == gift_card.tags.first().name
+ assert data["tag"] == gift_card.tag
assert data["isActive"]
assert data["initialBalance"]["amount"] == initial_balance
assert data["currentBalance"]["amount"] == initial_balance
@@ -417,8 +401,8 @@ def test_update_gift_card_balance(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
}
assert expected_event == data["events"][0]
@@ -460,7 +444,7 @@ def test_update_gift_card_change_to_never_expire(
assert not errors
assert data["displayCode"]
assert not data["expiryDate"]
- assert data["tags"][0]["name"] == gift_card.tags.first().name
+ assert data["tag"] == gift_card.tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
@@ -473,8 +457,8 @@ def test_update_gift_card_change_to_never_expire(
"app": None,
"balance": None,
"expiryDate": None,
- "tags": None,
- "oldTags": None,
+ "tag": None,
+ "oldTag": None,
"oldExpiryDate": old_expiry_date.isoformat(),
}
assert expected_event == data["events"][0]
@@ -597,40 +581,3 @@ def test_update_gift_card_date_in_past(
assert len(errors) == 1
assert errors[0]["field"] == "expiryDate"
assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
-
-
-def test_update_gift_card_duplicated_tags_item(
- staff_api_client,
- gift_card,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- gift_card_tag_list,
-):
- # given
- tag = gift_card_tag_list[0]
- variables = {
- "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
- "input": {"addTags": tag.name, "removeTags": tag.name},
- }
-
- # when
- response = staff_api_client.post_graphql(
- UPDATE_GIFT_CARD_MUTATION,
- variables,
- permissions=[
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- ],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["giftCardUpdate"]["errors"]
- data = content["data"]["giftCardUpdate"]["giftCard"]
-
- assert not data
- assert len(errors) == 1
- assert errors[0]["field"] == "tags"
- assert errors[0]["code"] == GiftCardErrorCode.DUPLICATED_INPUT_ITEM.name
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
index 8102380f8a..1b17dd3b82 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
@@ -20,9 +20,7 @@ QUERY_GIFT_CARD_BY_ID = """
displayCode
isActive
expiryDate
- tags {
- name
- }
+ tag
created
lastUsedOn
boughtInChannel
@@ -84,7 +82,7 @@ def test_query_gift_card_with_permissions(
assert data["displayCode"] == gift_card.display_code
assert data["isActive"] == gift_card.is_active
assert data["expiryDate"] is None
- assert data["tags"][0]["name"] == gift_card.tags.first().name
+ assert data["tag"] == gift_card.tag
assert data["created"] == gift_card.created.isoformat()
assert data["lastUsedOn"] == gift_card.last_used_on
assert data["boughtInChannel"] is None
@@ -149,7 +147,7 @@ def test_query_gift_card_by_app(
assert data["displayCode"] == gift_card.display_code
assert data["isActive"] == gift_card.is_active
assert data["expiryDate"] is None
- assert data["tags"][0]["name"] == gift_card.tags.first().name
+ assert data["tag"] == gift_card.tag
assert data["created"] == gift_card.created.isoformat()
assert data["lastUsedOn"] == gift_card.last_used_on
assert data["initialBalance"]["currency"] == gift_card.initial_balance.currency
@@ -383,8 +381,8 @@ QUERY_GIFT_CARD_EVENTS = """
email
orderId
orderNumber
- tags
- oldTags
+ tag
+ oldTag
balance {
initialBalance {
amount
@@ -456,8 +454,8 @@ def test_query_gift_card_events(
assert events_data[0]["email"] is None
assert events_data[0]["orderId"] is None
assert events_data[0]["orderNumber"] is None
- assert events_data[0]["tags"] is None
- assert events_data[0]["oldTags"] is None
+ assert events_data[0]["tag"] is None
+ assert events_data[0]["oldTag"] is None
assert events_data[0]["balance"] is None
assert events_data[0]["expiryDate"] is None
@@ -473,8 +471,8 @@ def test_query_gift_card_events(
assert events_data[1]["email"] == parameters["email"]
assert events_data[1]["orderId"] == graphene.Node.to_global_id("Order", order.pk)
assert events_data[1]["orderNumber"] == str(order.pk)
- assert events_data[1]["tags"] == parameters["tags"]
- assert events_data[1]["oldTags"] == parameters["old_tags"]
+ assert events_data[1]["tag"] == parameters["tag"]
+ assert events_data[1]["oldTag"] == parameters["old_tag"]
assert (
events_data[1]["balance"]["initialBalance"]["amount"]
== parameters["balance"]["initial_balance"]
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py
index 142bb473f0..3d10a7161c 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py
@@ -26,6 +26,49 @@ QUERY_GIFT_CARDS = """
"""
+ "filter_value, expected_gift_card_indexes",
+ [
+ ("test-tag", [0]),
+ ("another-tag", [1]),
+ ("tag", [0, 1, 2]),
+ ("not existing", []),
+ ("", [0, 1, 2]),
+ ],
+)
+def test_query_filter_gift_cards_by_tag(
+ filter_value,
+ expected_gift_card_indexes,
+ staff_api_client,
+ gift_card,
+ gift_card_expiry_date,
+ gift_card_used,
+ permission_manage_gift_card,
+):
+ # given
+ query = QUERY_GIFT_CARDS
+ gift_cards = [
+ gift_card,
+ gift_card_expiry_date,
+ gift_card_used,
+ ]
+ variables = {"filter": {"tag": filter_value}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_gift_card]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCards"]["edges"]
+ assert len(data) == len(expected_gift_card_indexes)
+ assert {card["node"]["id"] for card in data} == {
+ graphene.Node.to_global_id("GiftCard", gift_cards[i].pk)
+ for i in expected_gift_card_indexes
+ }
+
+
@pytest.mark.parametrize(
"filter_value, expected_gift_card_indexes",
[
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py
index a3dfb281b5..97792f3636 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py
@@ -177,3 +177,42 @@ def test_sorting_gift_cards_by_used_by(
assert [card["node"]["id"] for card in data] == [
graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_card_list
]
+
+
+ "direction",
+ ("ASC", "DESC"),
+)
+def test_sorting_gift_cards_by_tag(
+ direction,
+ staff_api_client,
+ gift_card,
+ gift_card_expiry_date,
+ gift_card_used,
+ permission_manage_gift_card,
+):
+ # given
+ gift_card_list = [gift_card_expiry_date, gift_card_used, gift_card]
+
+ variables = {
+ "sortBy": {
+ "direction": direction,
+ "field": "TAG",
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_GIFT_CARDS, variables, permissions=[permission_manage_gift_card]
+ )
+
+ # then
+ if direction == "DESC":
+ gift_card_list.reverse()
+
+ content = get_graphql_content(response)
+ data = content["data"]["giftCards"]["edges"]
+ assert len(data) == 3
+ assert [card["node"]["id"] for card in data] == [
+ graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_card_list
+ ]
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py
deleted file mode 100644
index 0d03e2796d..0000000000
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from ....tests.utils import assert_no_permission, get_graphql_content
-
-QUERY_GIFT_CARD_TAGS = """
- query giftCardTags{
- giftCardTags(first: 10) {
- edges {
- node {
- id
- name
- }
- }
- totalCount
- }
- }
-"""
-
-
-def test_query_gift_card_tags_by_staff(
- staff_api_client, gift_card_tag_list, permission_manage_gift_card
-):
- # given
- query = QUERY_GIFT_CARD_TAGS
-
- # when
- response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_gift_card]
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["giftCardTags"]["edges"]
- assert len(data) == len(gift_card_tag_list)
- assert {tag["node"]["name"] for tag in data} == {
- tag.name for tag in gift_card_tag_list
- }
-
-
-def test_query_gift_card_tags_by_app(
- app_api_client, gift_card_tag_list, permission_manage_gift_card
-):
- # given
- query = QUERY_GIFT_CARD_TAGS
-
- # when
- response = app_api_client.post_graphql(
- query, permissions=[permission_manage_gift_card]
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["giftCardTags"]["edges"]
- assert len(data) == len(gift_card_tag_list)
- assert {tag["node"]["name"] for tag in data} == {
- tag.name for tag in gift_card_tag_list
- }
-
-
-def test_query_gift_card_tags_by_customer(api_client, gift_card_tag_list):
- # given
- query = QUERY_GIFT_CARD_TAGS
-
- # when
- response = api_client.post_graphql(query)
-
- # then
- assert_no_permission(response)
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py
deleted file mode 100644
index b3738ecf25..0000000000
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py
+++ /dev/null
@@ -1,52 +0,0 @@
-import pytest
-
-from ....tests.utils import get_graphql_content
-
-QUERY_GIFT_CARD_TAGS = """
- query giftCardTags($filter: GiftCardTagFilterInput){
- giftCardTags(first: 10, filter: $filter) {
- edges {
- node {
- id
- name
- }
- }
- totalCount
- }
- }
-"""
-
-
- "value, expected_tag_indexes",
- [
- ("tag", [0, 1, 2, 3, 4]),
- ("test-tag", [0, 1, 2, 3, 4]),
- ("test", [0, 1, 2, 3, 4]),
- ("0", [0]),
- ("tag-3", [3]),
- ],
-)
-def test_filter_gift_card_tags_by_name(
- staff_api_client,
- gift_card_tag_list,
- permission_manage_gift_card,
- value,
- expected_tag_indexes,
-):
- # given
- query = QUERY_GIFT_CARD_TAGS
- variables = {"filter": {"search": value}}
-
- # when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_gift_card]
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["giftCardTags"]["edges"]
- assert len(data) == len(expected_tag_indexes)
- assert {tag["node"]["name"] for tag in data} == {
- gift_card_tag_list[index].name for index in expected_tag_indexes
- }
diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.py
index 6bc6bce998..b3c0798ca6 100644
--- a/saleor/graphql/giftcard/types.py
+++ b/saleor/graphql/giftcard/types.py
@@ -23,10 +23,7 @@ from ..meta.types import ObjectWithMetadata
from ..order.dataloaders import OrderByIdLoader
from ..product.dataloaders.products import ProductByIdLoader
from ..utils import get_user_or_app_from_context
-from .dataloaders import (
- GiftCardEventsByGiftCardIdLoader,
- GiftCardTagsByGiftCardIdLoader,
-)
+from .dataloaders import GiftCardEventsByGiftCardIdLoader
from .enums import GiftCardEventsEnum
@@ -70,14 +67,8 @@ class GiftCardEvent(CountableDjangoObjectType):
"User-friendly number of an order where gift card was used or bought."
)
)
- tags = graphene.List(
- graphene.NonNull(graphene.String),
- description="The list of gift card tags.",
- )
- old_tags = graphene.List(
- graphene.NonNull(graphene.String),
- description="The list of old gift card tags.",
- )
+ tag = graphene.String(description="The gift card tag.")
+ old_tag = graphene.String(description="Old gift card tag.")
balance = graphene.Field(GiftCardEventBalance, description="The gift card balance.")
expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")
old_expiry_date = graphene.types.datetime.Date(
@@ -139,12 +130,12 @@ class GiftCardEvent(CountableDjangoObjectType):
return str(order_id) if order_id else None
@staticmethod
- def resolve_tags(root: models.GiftCardEvent, _info):
- return root.parameters.get("tags")
+ def resolve_tag(root: models.GiftCardEvent, _info):
+ return root.parameters.get("tag")
@staticmethod
- def resolve_old_tags(root: models.GiftCardEvent, _info):
- return root.parameters.get("old_tags")
+ def resolve_old_tag(root: models.GiftCardEvent, _info):
+ return root.parameters.get("old_tag")
@staticmethod
@traced_resolver
@@ -181,14 +172,6 @@ class GiftCardEvent(CountableDjangoObjectType):
)
-class GiftCardTag(CountableDjangoObjectType):
- class Meta:
- description = f"{ADDED_IN_31} The gift card tag."
- model = models.GiftCardTag
- interfaces = [graphene.relay.Node]
- only_fields = ["id", "name"]
-
-
class GiftCard(CountableDjangoObjectType):
display_code = graphene.String(
description="Code in format which allows displaying in a user interface.",
@@ -235,11 +218,7 @@ class GiftCard(CountableDjangoObjectType):
description=f"{ADDED_IN_31} List of events associated with the gift card.",
required=True,
)
- tags = graphene.List(
- graphene.NonNull(GiftCardTag),
- description=f"{ADDED_IN_31} The gift card tag.",
- required=True,
- )
+ tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")
bought_in_channel = graphene.String(
description=(
"{ADDED_IN_31} Slug of the channel where the gift card was bought."
@@ -276,6 +255,7 @@ class GiftCard(CountableDjangoObjectType):
"initial_balance",
"current_balance",
"expiry_date",
+ "tag",
]
interfaces = [graphene.relay.Node, ObjectWithMetadata]
model = models.GiftCard
@@ -400,11 +380,6 @@ class GiftCard(CountableDjangoObjectType):
def resolve_events(root: models.GiftCard, _info):
return GiftCardEventsByGiftCardIdLoader(_info.context).load(root.id)
- @staticmethod
- @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)
- def resolve_tags(root: models.GiftCard, info):
- return GiftCardTagsByGiftCardIdLoader(info.context).load(root.id)
-
@staticmethod
@traced_resolver
def resolve_bought_in_channel(root: models.GiftCard, info):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 161fa8092d..08f9745578 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2276,6 +2276,7 @@ type GiftCard implements Node & ObjectWithMetadata {
code: String!
isActive: Boolean!
expiryDate: Date
+ tag: String
created: DateTime!
lastUsedOn: DateTime
initialBalance: Money
@@ -2291,7 +2292,6 @@ type GiftCard implements Node & ObjectWithMetadata {
app: App
product: Product
events: [GiftCardEvent!]!
- tags: [GiftCardTag!]!
boughtInChannel: String
user: User @deprecated(reason: "This field will be removed in Saleor 4.0. Use `createdBy` field instead.")
endDate: DateTime @deprecated(reason: "This field will be removed in Saleor 4.0. Use `expiryDate` field instead.")
@@ -2347,7 +2347,7 @@ type GiftCardCreate {
}
input GiftCardCreateInput {
- addTags: [String!]
+ tag: String
expiryDate: Date
startDate: Date
endDate: Date
@@ -2375,7 +2375,6 @@ type GiftCardError {
field: String
message: String
code: GiftCardErrorCode!
- tags: [String!]
}
enum GiftCardErrorCode {
@@ -2385,7 +2384,6 @@ enum GiftCardErrorCode {
NOT_FOUND
REQUIRED
UNIQUE
- DUPLICATED_INPUT_ITEM
}
type GiftCardEvent implements Node {
@@ -2398,8 +2396,8 @@ type GiftCardEvent implements Node {
email: String
orderId: ID
orderNumber: String
- tags: [String!]
- oldTags: [String!]
+ tag: String
+ oldTag: String
balance: GiftCardEventBalance
expiryDate: Date
oldExpiryDate: Date
@@ -2420,7 +2418,7 @@ enum GiftCardEventsEnum {
DEACTIVATED
BALANCE_RESET
EXPIRY_DATE_UPDATED
- TAGS_UPDATED
+ TAG_UPDATED
SENT_TO_CUSTOMER
RESENT
NOTE_ADDED
@@ -2430,6 +2428,7 @@ enum GiftCardEventsEnum {
input GiftCardFilterInput {
isActive: Boolean
metadata: [MetadataFilter]
+ tag: String
tags: [String]
products: [ID]
usedBy: [ID]
@@ -2483,6 +2482,7 @@ input GiftCardSettingsUpdateInput {
}
enum GiftCardSortField {
+ TAG
PRODUCT
USED_BY
CURRENT_BALANCE
@@ -2493,26 +2493,6 @@ input GiftCardSortingInput {
field: GiftCardSortField!
}
-type GiftCardTag implements Node {
- id: ID!
- name: String!
-}
-
-type GiftCardTagCountableConnection {
- pageInfo: PageInfo!
- edges: [GiftCardTagCountableEdge!]!
- totalCount: Int
-}
-
-type GiftCardTagCountableEdge {
- node: GiftCardTag!
- cursor: String!
-}
-
-input GiftCardTagFilterInput {
- search: String
-}
-
type GiftCardUpdate {
giftCardErrors: [GiftCardError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [GiftCardError!]!
@@ -2520,11 +2500,10 @@ type GiftCardUpdate {
}
input GiftCardUpdateInput {
- addTags: [String!]
+ tag: String
expiryDate: Date
startDate: Date
endDate: Date
- removeTags: [String!]
balanceAmount: PositiveDecimal
}
@@ -5907,7 +5886,6 @@ type Query {
giftCard(id: ID!): GiftCard
giftCards(sortBy: GiftCardSortingInput, filter: GiftCardFilterInput, before: String, after: String, first: Int, last: Int): GiftCardCountableConnection
giftCardCurrencies: [String!]!
- giftCardTags(filter: GiftCardTagFilterInput, before: String, after: String, first: Int, last: Int): GiftCardTagCountableConnection
plugin(id: ID!): Plugin
plugins(filter: PluginFilterInput, sortBy: PluginSortingInput, before: String, after: String, first: Int, last: Int): PluginCountableConnection
sale(id: ID!, channel: String): Sale
diff --git a/saleor/graphql/utils/validators.py b/saleor/graphql/utils/validators.py
index 9efcfeea49..a1482c18f3 100644
--- a/saleor/graphql/utils/validators.py
+++ b/saleor/graphql/utils/validators.py
@@ -1,6 +1,6 @@
from django.core.exceptions import ValidationError
-from ..core.utils import get_duplicates_items
+from ..core.utils import get_duplicates_ids
def check_for_duplicates(
@@ -11,15 +11,15 @@ def check_for_duplicates(
Raise error if some of items are duplicated.
"""
error = None
- duplicated_items = get_duplicates_items(
+ duplicated_ids = get_duplicates_ids(
input_data.get(add_field), input_data.get(remove_field)
)
- if duplicated_items:
+ if duplicated_ids:
# add error
error_msg = (
- "The same object cannot be in both list for adding and removing items."
+ "The same object cannot be in both list" "for adding and removing items."
)
- params = {error_class_field: list(duplicated_items)}
+ params = {error_class_field: list(duplicated_ids)}
error = ValidationError(message=error_msg, params=params)
return error
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 06ceb28cf2..27a4a79e26 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -57,7 +57,7 @@ from ..discount.models import (
VoucherTranslation,
)
from ..giftcard import GiftCardEvents
-from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
+from ..giftcard.models import GiftCard, GiftCardEvent
from ..menu.models import Menu, MenuItem, MenuItemTranslation
from ..order import OrderLineData, OrderOrigin, OrderStatus
from ..order.actions import cancel_fulfillment, fulfill_order_lines
@@ -3045,24 +3045,16 @@ def checkout_line_with_one_reservation(
return checkout_line
-def gift_card_tag_list(db):
- tags = [GiftCardTag(name=f"test-tag-{i}") for i in range(5)]
- return GiftCardTag.objects.bulk_create(tags)
-
-
@pytest.fixture
def gift_card(customer_user):
- gift_card = GiftCard.objects.create(
+ return GiftCard.objects.create(
code="never_expiry",
created_by=customer_user,
created_by_email=customer_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
+ tag="test-tag",
)
- tag, _ = GiftCardTag.objects.get_or_create(name="test-tag")
- gift_card.tags.add(tag)
- return gift_card
@pytest.fixture
@@ -3079,22 +3071,20 @@ def gift_card_with_metadata(customer_user):
@pytest.fixture
def gift_card_expiry_date(customer_user):
- gift_card = GiftCard.objects.create(
+ return GiftCard.objects.create(
code="expiry_date",
created_by=customer_user,
created_by_email=customer_user.email,
initial_balance=Money(20, "USD"),
current_balance=Money(20, "USD"),
expiry_date=datetime.date.today() + datetime.timedelta(days=100),
+ tag="another-tag",
)
- tag = GiftCardTag.objects.create(name="another-tag")
- gift_card.tags.add(tag)
- return gift_card
@pytest.fixture
def gift_card_used(staff_user, customer_user):
- gift_card = GiftCard.objects.create(
+ return GiftCard.objects.create(
code="giftcard_used",
created_by=staff_user,
used_by=customer_user,
@@ -3102,24 +3092,20 @@ def gift_card_used(staff_user, customer_user):
used_by_email=customer_user.email,
initial_balance=Money(100, "USD"),
current_balance=Money(80, "USD"),
+ tag="tag",
)
- tag = GiftCardTag.objects.create(name="tag")
- gift_card.tags.add(tag)
- return gift_card
@pytest.fixture
def gift_card_created_by_staff(staff_user):
- gift_card = GiftCard.objects.create(
+ return GiftCard.objects.create(
code="created_by_staff",
created_by=staff_user,
created_by_email=staff_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
+ tag="test-tag",
)
- tag, _ = GiftCardTag.objects.get_or_create(name="test-tag")
- gift_card.tags.add(tag)
- return gift_card
@pytest.fixture
@@ -3128,8 +3114,8 @@ def gift_card_event(gift_card, order, app, staff_user):
"message": "test message",
"email": "[email protected]",
"order_id": order.pk,
- "tags": ["test tag"],
- "old_tags": ["test old tag"],
+ "tag": "test tag",
+ "old_tag": "test old tag",
"balance": {
"currency": "USD",
"initial_balance": 10,