Skip to content

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

Add gift card tags query (#8339)

Iga Karbowiak813e842cc7c8
diff --git a/saleor/giftcard/__init__.py b/saleor/giftcard/__init__.py
index 00af1441ce..e451819c87 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"
- TAG_UPDATED = "tag_updated"
+ TAGS_UPDATED = "tags_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."),
- (TAG_UPDATED, "The gift card tag 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."),
diff --git a/saleor/giftcard/error_codes.py b/saleor/giftcard/error_codes.py
index c81ddbe3cd..1415313be6 100644
--- a/saleor/giftcard/error_codes.py
+++ b/saleor/giftcard/error_codes.py
@@ -8,3 +8,4 @@ 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 dfff1dfe7b..ed2b123900 100644
--- a/saleor/giftcard/events.py
+++ b/saleor/giftcard/events.py
@@ -1,4 +1,4 @@
-from typing import Iterable, Optional, Tuple
+from typing import Iterable, List, 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_tag_updated_event(
+def gift_card_tags_updated_event(
gift_card: GiftCard,
- old_gift_card: GiftCard,
+ old_tags: List[str],
user: UserType,
app: AppType,
):
@@ -112,10 +112,12 @@ def gift_card_tag_updated_event(
gift_card=gift_card,
user=user,
app=app,
- type=GiftCardEvents.TAG_UPDATED,
+ type=GiftCardEvents.TAGS_UPDATED,
parameters={
- "tag": gift_card.tag,
- "old_tag": old_gift_card.tag,
+ "tags": list(
+ gift_card.tags.order_by("name").values_list("name", flat=True)
+ ),
+ "old_tags": old_tags,
},
)
diff --git a/saleor/giftcard/migrations/0010_auto_20211007_0546.py b/saleor/giftcard/migrations/0010_auto_20211007_0546.py
new file mode 100644
index 0000000000..62e1f057fb
--- /dev/null
+++ b/saleor/giftcard/migrations/0010_auto_20211007_0546.py
@@ -0,0 +1,57 @@
+# 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
new file mode 100644
index 0000000000..84ea1efba0
--- /dev/null
+++ b/saleor/giftcard/migrations/0011_auto_20211007_0547.py
@@ -0,0 +1,23 @@
+# 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
new file mode 100644
index 0000000000..4433ff3631
--- /dev/null
+++ b/saleor/giftcard/migrations/0012_auto_20211007_0655.py
@@ -0,0 +1,38 @@
+# 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 9b733a0135..878cad1015 100644
--- a/saleor/giftcard/models.py
+++ b/saleor/giftcard/models.py
@@ -14,6 +14,21 @@ 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(
@@ -51,7 +66,7 @@ class GiftCard(ModelWithMetadata):
expiry_date = models.DateField(null=True, blank=True)
- tag = models.CharField(max_length=255, null=True, blank=True)
+ tags = models.ManyToManyField(GiftCardTag, "gift_cards")
created = models.DateTimeField(auto_now_add=True)
last_used_on = models.DateTimeField(null=True, blank=True)
product = models.ForeignKey(
@@ -97,15 +112,6 @@ 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 3d9c880f58..2bb3dbca63 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_ids
+from ..core.utils import get_duplicated_values, get_duplicates_items
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_ids(add_channels_ids, remove_channels_ids)
+ duplicated_ids = get_duplicates_items(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 2e06f7b528..741721a207 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -316,6 +316,11 @@ 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 1bae07f2bf..8e24fee864 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_ids(first_list, second_list):
+def get_duplicates_items(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 8627552f7c..a57987d5f7 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
+from ...giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
from ..core.dataloaders import DataLoader
@@ -24,3 +24,22 @@ 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 2c4bdb6705..19c3910a47 100644
--- a/saleor/graphql/giftcard/filters.py
+++ b/saleor/graphql/giftcard/filters.py
@@ -15,12 +15,6 @@ 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(
@@ -50,7 +44,8 @@ def filter_gift_cards_by_used_by_user(qs, user_pks):
def filter_tags_list(qs, _, value):
if not value:
return qs
- return qs.filter(tag__in=value)
+ tags = models.GiftCardTag.objects.filter(name__in=value)
+ return qs.filter(Exists(tags.filter(pk=OuterRef("tags__id"))))
def filter_currency(qs, _, value):
@@ -75,7 +70,6 @@ def filter_code(qs, _, value):
class GiftCardFilter(django_filters.FilterSet):
- 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)
@@ -113,3 +107,18 @@ 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 b1f0d7af1a..25ea8e7c7b 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -1,4 +1,5 @@
from copy import deepcopy
+from typing import Iterable
import graphene
from django.core.exceptions import ValidationError
@@ -6,6 +7,7 @@ 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
@@ -18,11 +20,15 @@ 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):
- tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")
+ add_tags = graphene.List(
+ graphene.NonNull(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."
)
@@ -70,6 +76,10 @@ 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
)
@@ -206,6 +216,26 @@ 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:
@@ -237,6 +267,13 @@ 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)
@@ -244,25 +281,51 @@ 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, info.context.user, info.context.app
- )
+ events.gift_card_balance_reset_event(instance, old_instance, user, app)
if "expiry_date" in cleaned_input:
events.gift_card_expiry_date_updated_event(
- 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
+ instance, old_instance, user, 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 518e90c0d8..beeadfcf0b 100644
--- a/saleor/graphql/giftcard/resolvers.py
+++ b/saleor/graphql/giftcard/resolvers.py
@@ -7,3 +7,7 @@ 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 41fd050b20..a05705582d 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
+from .filters import GiftCardFilterInput, GiftCardTagFilterInput
from .mutations import (
GiftCardActivate,
GiftCardAddNote,
@@ -22,9 +22,9 @@ from .mutations import (
GiftCardResend,
GiftCardUpdate,
)
-from .resolvers import resolve_gift_card, resolve_gift_cards
+from .resolvers import resolve_gift_card, resolve_gift_card_tags, resolve_gift_cards
from .sorters import GiftCardSortingInput
-from .types import GiftCard
+from .types import GiftCard, GiftCardTag
class GiftCardQueries(graphene.ObjectType):
@@ -48,6 +48,13 @@ 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):
@@ -68,6 +75,10 @@ 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 62b7d1438d..68e5b831d3 100644
--- a/saleor/graphql/giftcard/sorters.py
+++ b/saleor/graphql/giftcard/sorters.py
@@ -4,7 +4,6 @@ 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 90d73a6ceb..d1b68bc800 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
+from .....giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
GIFT_CARD_COUNT_IN_BENCHMARKS = 20
@@ -23,11 +23,12 @@ 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 8ec0783591..c9e2c73492 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
@@ -8,19 +8,23 @@ from ....tests.utils import get_graphql_content
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
- $balance: PriceInput!, $userEmail: String, $tag: String, $channel: String,
- $note: String, $expiryDate: Date, $isActive: Boolean!
+ $balance: PriceInput!, $userEmail: String, $addTags: [String!],
+ $channel: String, $note: String, $expiryDate: Date, $isActive: Boolean!
){
giftCardCreate(input: {
- balance: $balance, userEmail: $userEmail, tag: $tag, channel: $channel,
- expiryDate: $expiryDate, note: $note, isActive: $isActive }) {
+ balance: $balance, userEmail: $userEmail, addTags: $addTags,
+ channel: $channel, expiryDate: $expiryDate, note: $note,
+ isActive: $isActive
+ }) {
giftCard {
id
code
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
initialBalance {
@@ -105,7 +109,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"expiry_date": None,
"isActive": True,
@@ -140,7 +144,9 @@ UPDATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
initialBalance {
@@ -218,12 +224,14 @@ 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,
- "tag": tag,
+ "addTags": [tag],
+ "removeTags": [old_tag.name],
"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 57fa521fd7..59a5e5e51b 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
- tag
- oldTag
+ tags
+ oldTags
balance {
initialBalance {
amount
@@ -53,7 +53,9 @@ FRAGMENT_GIFT_CARD_DETAILS = (
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
boughtInChannel
@@ -168,7 +170,7 @@ def test_query_gift_cards(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_filter_gift_cards_by_tag(
+def test_filter_gift_cards_by_tags(
staff_api_client,
gift_cards_for_benchmarks,
permission_manage_gift_card,
@@ -193,7 +195,7 @@ def test_filter_gift_cards_by_tag(
content = get_graphql_content(
staff_api_client.post_graphql(
query,
- {"filter": {"tag": "tag"}},
+ {"filter": {"tags": ["benchmark-test-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 b164a16377..82359087ad 100644
--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
@@ -21,7 +21,9 @@ CREATE_GIFT_CARD_MUTATION = """
startDate
endDate
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
initialBalance {
@@ -67,7 +69,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tag": tag,
+ "tags": [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 2a00a5ce84..791875dc4a 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -17,7 +17,9 @@ CREATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
initialBalance {
@@ -90,11 +92,14 @@ 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"
- tag = "gift-card-tag"
+ new_tag = "gift-card-tag"
+ existing_tag_name = gift_card_tag_list[0].name
+ tags = [new_tag, existing_tag_name]
note = "This is gift card note that will be save in gift card event."
variables = {
"input": {
@@ -104,7 +109,7 @@ def test_create_never_expiry_gift_card(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tag": tag,
+ "addTags": tags,
"note": note,
"isActive": True,
}
@@ -130,7 +135,8 @@ def test_create_never_expiry_gift_card(
assert data["code"]
assert data["displayCode"]
assert not data["expiryDate"]
- assert data["tag"] == tag
+ assert len(data["tags"]) == 2
+ assert {tag["name"] for tag in data["tags"]} == set(tags)
assert data["createdBy"]["email"] == staff_api_client.user.email
assert data["createdByEmail"] == staff_api_client.user.email
assert not data["usedBy"]
@@ -191,7 +197,7 @@ def test_create_gift_card_by_app(
"amount": initial_balance,
"currency": currency,
},
- "tag": tag,
+ "addTags": [tag],
"note": note,
"expiryDate": None,
"isActive": False,
@@ -214,7 +220,8 @@ def test_create_gift_card_by_app(
assert data["code"]
assert data["displayCode"]
assert not data["expiryDate"]
- assert data["tag"] == tag
+ assert len(data["tags"]) == 1
+ assert data["tags"][0]["name"] == tag
assert not data["createdBy"]
assert not data["createdByEmail"]
assert not data["usedBy"]
@@ -259,7 +266,7 @@ def test_create_gift_card_by_customer(api_client, customer_user, channel_USD):
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"expiryDate": None,
"isActive": True,
@@ -287,7 +294,7 @@ def test_create_gift_card_no_premissions(staff_api_client):
"amount": initial_balance,
"currency": currency,
},
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"expiryDate": None,
"isActive": True,
@@ -322,7 +329,7 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount(
"currency": currency,
},
"userEmail": customer_user.email,
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -367,7 +374,7 @@ def test_create_gift_card_with_malformed_email(
"currency": currency,
},
"userEmail": "malformed",
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -414,7 +421,7 @@ def test_create_gift_card_lack_of_channel(
"currency": currency,
},
"userEmail": customer_user.email,
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -460,7 +467,7 @@ def test_create_gift_card_with_zero_balance_amount(
"currency": currency,
},
"userEmail": customer_user.email,
- "tag": tag,
+ "addTags": [tag],
"note": "This is gift card note that will be save in gift card event.",
"isActive": True,
}
@@ -511,7 +518,7 @@ def test_create_gift_card_with_expiry_date(
},
"userEmail": customer_user.email,
"channel": channel_USD.slug,
- "tag": tag,
+ "addTags": [tag],
"expiryDate": date_value,
"isActive": True,
}
@@ -584,7 +591,7 @@ def test_create_gift_card_with_expiry_date_type_invalid(
"currency": currency,
},
"userEmail": customer_user.email,
- "tag": tag,
+ "addTags": [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 ce52944213..d34cf2cfc0 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
@@ -5,6 +5,7 @@ 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 = """
@@ -17,7 +18,9 @@ UPDATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
initialBalance {
@@ -50,8 +53,8 @@ UPDATE_GIFT_CARD_MUTATION = """
app {
name
}
- tag
- oldTag
+ tags
+ oldTags
balance {
initialBalance {
amount
@@ -94,17 +97,18 @@ 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)
- tag = "new-gift-card-tag"
+ old_tag = gift_card.tags.first().name
+ new_tag = "new-gift-card-tag"
+ tags_count = GiftCardTag.objects.count()
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "tag": tag,
+ "addTags": [new_tag],
"expiryDate": date_value,
},
}
@@ -128,7 +132,8 @@ def test_update_gift_card(
assert not errors
assert data["displayCode"]
assert data["expiryDate"] == date_value.isoformat()
- assert data["tag"] == tag
+ assert len(data["tags"]) == 2
+ assert {tag["name"] for tag in data["tags"]} == {old_tag, new_tag}
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
assert not data["usedBy"]
@@ -167,8 +172,8 @@ def test_update_gift_card(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
},
{
"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
@@ -179,11 +184,11 @@ def test_update_gift_card(
"balance": None,
"expiryDate": date_value.isoformat(),
"oldExpiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
},
{
- "type": GiftCardEvents.TAG_UPDATED.upper(),
+ "type": GiftCardEvents.TAGS_UPDATED.upper(),
"user": {
"email": staff_api_client.user.email,
},
@@ -191,13 +196,15 @@ def test_update_gift_card(
"balance": None,
"expiryDate": None,
"oldExpiryDate": None,
- "tag": tag,
- "oldTag": old_tag,
+ "tags": [new_tag, old_tag],
+ "oldTags": [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,
@@ -205,21 +212,24 @@ 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.tag
+ old_tag = gift_card.tags.first()
initial_balance = 100.0
currency = gift_card.currency
date_value = date.today() + timedelta(days=365)
- tag = "new-gift-card-tag"
+ new_tag = gift_card_tag_list[0].name
+ tags_count = GiftCardTag.objects.count()
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
"balanceAmount": initial_balance,
- "tag": tag,
+ "addTags": [new_tag],
+ "removeTags": [old_tag.name],
"expiryDate": date_value,
},
}
@@ -243,7 +253,8 @@ def test_update_gift_card_by_app(
assert not errors
assert data["displayCode"]
assert data["expiryDate"] == date_value.isoformat()
- assert data["tag"] == tag
+ assert len(data["tags"]) == 1
+ assert {tag["name"] for tag in data["tags"]} == {new_tag}
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
assert not data["usedBy"]
@@ -280,8 +291,8 @@ def test_update_gift_card_by_app(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
},
{
"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
@@ -290,23 +301,28 @@ def test_update_gift_card_by_app(
"balance": None,
"expiryDate": date_value.isoformat(),
"oldExpiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
},
{
- "type": GiftCardEvents.TAG_UPDATED.upper(),
+ "type": GiftCardEvents.TAGS_UPDATED.upper(),
"user": None,
"app": {"name": app_api_client.app.name},
"balance": None,
"expiryDate": None,
"oldExpiryDate": None,
- "tag": tag,
- "oldTag": old_tag,
+ "tags": [new_tag],
+ "oldTags": [old_tag.name],
},
]
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
@@ -316,7 +332,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,
- "tag": tag,
+ "addTags": [tag],
},
}
@@ -369,7 +385,7 @@ def test_update_gift_card_balance(
assert not errors
assert not data["expiryDate"]
- assert data["tag"] == gift_card.tag
+ assert data["tags"][0]["name"] == gift_card.tags.first().name
assert data["isActive"]
assert data["initialBalance"]["amount"] == initial_balance
assert data["currentBalance"]["amount"] == initial_balance
@@ -401,8 +417,8 @@ def test_update_gift_card_balance(
},
"expiryDate": None,
"oldExpiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
}
assert expected_event == data["events"][0]
@@ -444,7 +460,7 @@ def test_update_gift_card_change_to_never_expire(
assert not errors
assert data["displayCode"]
assert not data["expiryDate"]
- assert data["tag"] == gift_card.tag
+ assert data["tags"][0]["name"] == gift_card.tags.first().name
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
@@ -457,8 +473,8 @@ def test_update_gift_card_change_to_never_expire(
"app": None,
"balance": None,
"expiryDate": None,
- "tag": None,
- "oldTag": None,
+ "tags": None,
+ "oldTags": None,
"oldExpiryDate": old_expiry_date.isoformat(),
}
assert expected_event == data["events"][0]
@@ -581,3 +597,40 @@ 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 1b17dd3b82..8102380f8a 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
@@ -20,7 +20,9 @@ QUERY_GIFT_CARD_BY_ID = """
displayCode
isActive
expiryDate
- tag
+ tags {
+ name
+ }
created
lastUsedOn
boughtInChannel
@@ -82,7 +84,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["tag"] == gift_card.tag
+ assert data["tags"][0]["name"] == gift_card.tags.first().name
assert data["created"] == gift_card.created.isoformat()
assert data["lastUsedOn"] == gift_card.last_used_on
assert data["boughtInChannel"] is None
@@ -147,7 +149,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["tag"] == gift_card.tag
+ assert data["tags"][0]["name"] == gift_card.tags.first().name
assert data["created"] == gift_card.created.isoformat()
assert data["lastUsedOn"] == gift_card.last_used_on
assert data["initialBalance"]["currency"] == gift_card.initial_balance.currency
@@ -381,8 +383,8 @@ QUERY_GIFT_CARD_EVENTS = """
email
orderId
orderNumber
- tag
- oldTag
+ tags
+ oldTags
balance {
initialBalance {
amount
@@ -454,8 +456,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]["tag"] is None
- assert events_data[0]["oldTag"] is None
+ assert events_data[0]["tags"] is None
+ assert events_data[0]["oldTags"] is None
assert events_data[0]["balance"] is None
assert events_data[0]["expiryDate"] is None
@@ -471,8 +473,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]["tag"] == parameters["tag"]
- assert events_data[1]["oldTag"] == parameters["old_tag"]
+ assert events_data[1]["tags"] == parameters["tags"]
+ assert events_data[1]["oldTags"] == parameters["old_tags"]
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 162c2e8a45..c8bbbb4971 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py
@@ -22,49 +22,6 @@ 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 97792f3636..a3dfb281b5 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py
@@ -177,42 +177,3 @@ 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
new file mode 100644
index 0000000000..0d03e2796d
--- /dev/null
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py
@@ -0,0 +1,66 @@
+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
new file mode 100644
index 0000000000..b3738ecf25
--- /dev/null
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py
@@ -0,0 +1,52 @@
+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 b3c0798ca6..6bc6bce998 100644
--- a/saleor/graphql/giftcard/types.py
+++ b/saleor/graphql/giftcard/types.py
@@ -23,7 +23,10 @@ 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
+from .dataloaders import (
+ GiftCardEventsByGiftCardIdLoader,
+ GiftCardTagsByGiftCardIdLoader,
+)
from .enums import GiftCardEventsEnum
@@ -67,8 +70,14 @@ class GiftCardEvent(CountableDjangoObjectType):
"User-friendly number of an order where gift card was used or bought."
)
)
- tag = graphene.String(description="The gift card tag.")
- old_tag = graphene.String(description="Old gift card tag.")
+ 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.",
+ )
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(
@@ -130,12 +139,12 @@ class GiftCardEvent(CountableDjangoObjectType):
return str(order_id) if order_id else None
@staticmethod
- def resolve_tag(root: models.GiftCardEvent, _info):
- return root.parameters.get("tag")
+ def resolve_tags(root: models.GiftCardEvent, _info):
+ return root.parameters.get("tags")
@staticmethod
- def resolve_old_tag(root: models.GiftCardEvent, _info):
- return root.parameters.get("old_tag")
+ def resolve_old_tags(root: models.GiftCardEvent, _info):
+ return root.parameters.get("old_tags")
@staticmethod
@traced_resolver
@@ -172,6 +181,14 @@ 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.",
@@ -218,7 +235,11 @@ class GiftCard(CountableDjangoObjectType):
description=f"{ADDED_IN_31} List of events associated with the gift card.",
required=True,
)
- tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")
+ tags = graphene.List(
+ graphene.NonNull(GiftCardTag),
+ description=f"{ADDED_IN_31} The gift card tag.",
+ required=True,
+ )
bought_in_channel = graphene.String(
description=(
"{ADDED_IN_31} Slug of the channel where the gift card was bought."
@@ -255,7 +276,6 @@ class GiftCard(CountableDjangoObjectType):
"initial_balance",
"current_balance",
"expiry_date",
- "tag",
]
interfaces = [graphene.relay.Node, ObjectWithMetadata]
model = models.GiftCard
@@ -380,6 +400,11 @@ 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 c569511cb2..7e32eb83bf 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2276,7 +2276,6 @@ type GiftCard implements Node & ObjectWithMetadata {
code: String!
isActive: Boolean!
expiryDate: Date
- tag: String
created: DateTime!
lastUsedOn: DateTime
initialBalance: Money
@@ -2292,6 +2291,7 @@ 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 {
- tag: String
+ addTags: [String!]
expiryDate: Date
startDate: Date
endDate: Date
@@ -2375,6 +2375,7 @@ type GiftCardError {
field: String
message: String
code: GiftCardErrorCode!
+ tags: [String!]
}
enum GiftCardErrorCode {
@@ -2384,6 +2385,7 @@ enum GiftCardErrorCode {
NOT_FOUND
REQUIRED
UNIQUE
+ DUPLICATED_INPUT_ITEM
}
type GiftCardEvent implements Node {
@@ -2396,8 +2398,8 @@ type GiftCardEvent implements Node {
email: String
orderId: ID
orderNumber: String
- tag: String
- oldTag: String
+ tags: [String!]
+ oldTags: [String!]
balance: GiftCardEventBalance
expiryDate: Date
oldExpiryDate: Date
@@ -2418,7 +2420,7 @@ enum GiftCardEventsEnum {
DEACTIVATED
BALANCE_RESET
EXPIRY_DATE_UPDATED
- TAG_UPDATED
+ TAGS_UPDATED
SENT_TO_CUSTOMER
RESENT
NOTE_ADDED
@@ -2427,7 +2429,6 @@ enum GiftCardEventsEnum {
input GiftCardFilterInput {
isActive: Boolean
- tag: String
tags: [String]
products: [ID]
usedBy: [ID]
@@ -2481,7 +2482,6 @@ input GiftCardSettingsUpdateInput {
}
enum GiftCardSortField {
- TAG
PRODUCT
USED_BY
CURRENT_BALANCE
@@ -2492,6 +2492,26 @@ 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!]!
@@ -2499,10 +2519,11 @@ type GiftCardUpdate {
}
input GiftCardUpdateInput {
- tag: String
+ addTags: [String!]
expiryDate: Date
startDate: Date
endDate: Date
+ removeTags: [String!]
balanceAmount: PositiveDecimal
}
@@ -5885,6 +5906,7 @@ 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 a1482c18f3..9efcfeea49 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_ids
+from ..core.utils import get_duplicates_items
def check_for_duplicates(
@@ -11,15 +11,15 @@ def check_for_duplicates(
Raise error if some of items are duplicated.
"""
error = None
- duplicated_ids = get_duplicates_ids(
+ duplicated_items = get_duplicates_items(
input_data.get(add_field), input_data.get(remove_field)
)
- if duplicated_ids:
+ if duplicated_items:
# 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_ids)}
+ params = {error_class_field: list(duplicated_items)}
error = ValidationError(message=error_msg, params=params)
return error
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index d8b1bac8b9..98cb6113e5 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
+from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTag
from ..menu.models import Menu, MenuItem, MenuItemTranslation
from ..order import OrderLineData, OrderOrigin, OrderStatus
from ..order.actions import cancel_fulfillment, fulfill_order_lines
@@ -3045,34 +3045,44 @@ 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):
- return GiftCard.objects.create(
+ gift_card = 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
def gift_card_expiry_date(customer_user):
- return GiftCard.objects.create(
+ gift_card = 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):
- return GiftCard.objects.create(
+ gift_card = GiftCard.objects.create(
code="giftcard_used",
created_by=staff_user,
used_by=customer_user,
@@ -3080,20 +3090,24 @@ 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):
- return GiftCard.objects.create(
+ gift_card = 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
@@ -3102,8 +3116,8 @@ def gift_card_event(gift_card, order, app, staff_user):
"message": "test message",
"email": "[email protected]",
"order_id": order.pk,
- "tag": "test tag",
- "old_tag": "test old tag",
+ "tags": ["test tag"],
+ "old_tags": ["test old tag"],
"balance": {
"currency": "USD",
"initial_balance": 10,