Skip to content

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

Set expiry date when gift card is created, allow defining only expiry date in gift card mutations

IKarbowiakbe135374d5f0
diff --git a/saleor/giftcard/__init__.py b/saleor/giftcard/__init__.py
index 3124796766..c94e4548b0 100644
--- a/saleor/giftcard/__init__.py
+++ b/saleor/giftcard/__init__.py
@@ -1,17 +1,3 @@
-class GiftCardExpiryType:
- """The gift card expiry options."""
-
- NEVER_EXPIRE = "never_expire"
- EXPIRY_PERIOD = "expiry_period"
- EXPIRY_DATE = "expiry_date"
-
- CHOICES = [
- (NEVER_EXPIRE, "Never expire"),
- (EXPIRY_PERIOD, "Expiry period"),
- (EXPIRY_DATE, "Expiry date"),
- ]
-
-
class GiftCardEvents:
"""The different gift card event types."""
@@ -21,8 +7,7 @@ class GiftCardEvents:
ACTIVATED = "activated"
DEACTIVATED = "deactivated"
BALANCE_RESET = "balance_reset"
- EXPIRY_SETTINGS_UPDATED = "expiry_settings_updated"
- EXPIRY_DATE_SET = "expiry_date_set"
+ EXPIRY_DATE_UPDATED = "expiry_date_updated"
SENT_TO_CUSTOMER = "sent_to_customer"
RESENT = "resent"
NOTE_ADDED = "note_added"
@@ -35,8 +20,7 @@ class GiftCardEvents:
(ACTIVATED, "The gift card was activated."),
(DEACTIVATED, "The gift card was deactivated."),
(BALANCE_RESET, "The gift card balance was reset."),
- (EXPIRY_SETTINGS_UPDATED, "The gift card expiry settings was updated."),
- (EXPIRY_DATE_SET, "The expiry date was set."),
+ (EXPIRY_DATE_UPDATED, "The gift card expiry date 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/events.py b/saleor/giftcard/events.py
index 162e8d5007..2864e818a9 100644
--- a/saleor/giftcard/events.py
+++ b/saleor/giftcard/events.py
@@ -1,4 +1,3 @@
-from datetime import date
from typing import Iterable, Optional, Tuple
from ..account.models import User
@@ -28,7 +27,7 @@ def gift_card_issued_event(
user=user,
app=app,
type=GiftCardEvents.ISSUED,
- parameters={"balance": balance_data},
+ parameters={"balance": balance_data, "expiry_date": gift_card.expiry_date},
)
@@ -99,7 +98,7 @@ def gift_card_balance_reset(
)
-def gift_card_expiry_settings_updated(
+def gift_card_expiry_date_updated(
gift_card: GiftCard,
old_gift_card: GiftCard,
user: UserType,
@@ -107,22 +106,15 @@ def gift_card_expiry_settings_updated(
):
if not user_is_valid(user):
user = None
- expiry_data = {
- "expiry_type": gift_card.expiry_type,
- "expiry_period": gift_card.expiry_period,
- "expiry_period_type": gift_card.expiry_period_type,
- "expiry_date": gift_card.expiry_date,
- "old_expiry_type": old_gift_card.expiry_type,
- "old_expiry_period": old_gift_card.expiry_period,
- "old_expiry_period_type": old_gift_card.expiry_period_type,
- "old_expiry_date": old_gift_card.expiry_date,
- }
return GiftCardEvent.objects.create(
gift_card=gift_card,
user=user,
app=app,
- type=GiftCardEvents.EXPIRY_SETTINGS_UPDATED,
- parameters={"expiry": expiry_data},
+ type=GiftCardEvents.EXPIRY_DATE_UPDATED,
+ parameters={
+ "expiry_date": gift_card.expiry_date,
+ "old_expiry_date": old_gift_card.expiry_date,
+ },
)
@@ -208,26 +200,6 @@ def gift_card_note_added(
)
-def gift_cards_expiry_date_set(
- expiry_data: Iterable[Tuple[int, date]],
- user: UserType,
- app: AppType,
-):
- if not user_is_valid(user):
- user = None
- events = [
- GiftCardEvent(
- gift_card_id=gift_card_id,
- user=user,
- app=app,
- type=GiftCardEvents.EXPIRY_DATE_SET,
- parameters={"expiry": {"expiry_date": expiry_date}},
- )
- for gift_card_id, expiry_date in expiry_data
- ]
- return GiftCardEvent.objects.bulk_create(events)
-
-
def gift_cards_used_in_order(
balance_data: Iterable[Tuple[GiftCard, float]],
order_id: int,
@@ -267,7 +239,7 @@ def gift_cards_bought(
user=user,
app=app,
type=GiftCardEvents.BOUGHT,
- parameters={"order_id": order_id},
+ parameters={"order_id": order_id, "expiry_date": gift_card.expiry_date},
)
for gift_card in gift_cards
]
diff --git a/saleor/giftcard/migrations/0010_auto_20210818_0633.py b/saleor/giftcard/migrations/0010_auto_20210818_0633.py
new file mode 100644
index 0000000000..60172068a4
--- /dev/null
+++ b/saleor/giftcard/migrations/0010_auto_20210818_0633.py
@@ -0,0 +1,45 @@
+# Generated by Django 3.2.5 on 2021-08-18 06:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("giftcard", "0009_alter_giftcard_expiry_period_type"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="giftcard",
+ name="expiry_period",
+ ),
+ migrations.RemoveField(
+ model_name="giftcard",
+ name="expiry_period_type",
+ ),
+ migrations.RemoveField(
+ model_name="giftcard",
+ name="expiry_type",
+ ),
+ 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."),
+ ("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 a40e58c2bd..d9f331b1e0 100644
--- a/saleor/giftcard/models.py
+++ b/saleor/giftcard/models.py
@@ -8,11 +8,10 @@ from django.utils import timezone
from django_prices.models import MoneyField
from ..app.models import App
-from ..core import TimePeriodType
from ..core.models import ModelWithMetadata
from ..core.permissions import GiftcardPermissions
from ..core.utils.json_serializer import CustomJsonEncoder
-from . import GiftCardEvents, GiftCardExpiryType
+from . import GiftCardEvents
class GiftCardQueryset(models.QuerySet):
@@ -51,14 +50,6 @@ class GiftCard(ModelWithMetadata):
)
expiry_date = models.DateField(null=True, blank=True)
- expiry_type = models.CharField(
- max_length=32,
- choices=GiftCardExpiryType.CHOICES,
- )
- expiry_period_type = models.CharField(
- max_length=32, choices=TimePeriodType.CHOICES, null=True, blank=True
- )
- expiry_period = models.PositiveIntegerField(null=True, blank=True)
tag = models.CharField(max_length=255, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index 99e743435f..41238e866f 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -5,8 +5,10 @@ import pytest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
+from ...core import TimePeriodType
from ...core.utils.promo_code import InvalidPromoCode
from ...plugins.manager import get_plugins_manager
+from ...site import GiftCardSettingsExpiryType
from .. import GiftCardEvents
from ..models import GiftCardEvent
from ..utils import (
@@ -137,30 +139,32 @@ def test_remove_gift_card_code_from_checkout_no_checkout_gift_cards(
@pytest.mark.parametrize(
"period_type, period", [("years", 5), ("weeks", 1), ("months", 13), ("days", 100)]
)
-def test_calculate_expiry_settings(period_type, period, gift_card_expiry_period):
+def test_calculate_expiry_settings(period_type, period, site_settings):
# given
- gift_card_expiry_period.expiry_period_type = period_type.rstrip("s")
- gift_card_expiry_period.expiry_period = period
- gift_card_expiry_period.save(update_fields=["expiry_period_type", "expiry_period"])
+ site_settings.gift_card_expiry_type = GiftCardSettingsExpiryType.EXPIRY_PERIOD
+ site_settings.gift_card_expiry_period_type = period_type.rstrip("s")
+ site_settings.gift_card_expiry_period = period
+ site_settings.save(
+ update_fields=[
+ "gift_card_expiry_type",
+ "gift_card_expiry_period_type",
+ "gift_card_expiry_period",
+ ]
+ )
# when
- expiry_date = calculate_expiry_date(gift_card_expiry_period)
+ expiry_date = calculate_expiry_date(site_settings)
# then
assert expiry_date == timezone.now().date() + relativedelta(**{period_type: period})
-def test_calculate_expiry_settings_for_never_expire_gift_card(gift_card):
- # when
- expiry_date = calculate_expiry_date(gift_card)
-
- # then
- assert expiry_date is None
-
+def test_calculate_expiry_settings_for_never_expire_settings(site_settings):
+ # given
+ site_settings.gift_card_expiry_type = GiftCardSettingsExpiryType.NEVER_EXPIRE
-def test_calculate_expiry_settings_for_expire_date_gift_card(gift_card_expiry_date):
# when
- expiry_date = calculate_expiry_date(gift_card_expiry_date)
+ expiry_date = calculate_expiry_date(site_settings)
# then
assert expiry_date is None
@@ -198,9 +202,7 @@ def test_gift_cards_create(
assert shippable_gift_card.current_balance == shippable_price
assert shippable_gift_card.created_by == order.user
assert shippable_gift_card.created_by_email == user_email
- assert shippable_gift_card.expiry_type == site_settings.gift_card_expiry_type
- assert shippable_gift_card.expiry_period_type is None
- assert shippable_gift_card.expiry_period is None
+ assert shippable_gift_card.expiry_date is None
bought_event_for_shippable_card = GiftCardEvent.objects.get(
gift_card=shippable_gift_card
@@ -208,7 +210,10 @@ def test_gift_cards_create(
assert bought_event_for_shippable_card.user == staff_user
assert bought_event_for_shippable_card.app is None
assert bought_event_for_shippable_card.type == GiftCardEvents.BOUGHT
- assert bought_event_for_shippable_card.parameters == {"order_id": order.id}
+ assert bought_event_for_shippable_card.parameters == {
+ "order_id": order.id,
+ "expiry_date": None,
+ }
non_shippable_gift_card = gift_cards[1]
non_shippable_price = gift_card_non_shippable_order_line.total_price_gross
@@ -216,9 +221,7 @@ def test_gift_cards_create(
assert non_shippable_gift_card.current_balance == non_shippable_price
assert non_shippable_gift_card.created_by == order.user
assert non_shippable_gift_card.created_by_email == user_email
- assert non_shippable_gift_card.expiry_type == site_settings.gift_card_expiry_type
- assert non_shippable_gift_card.expiry_period_type is None
- assert non_shippable_gift_card.expiry_period is None
+ assert non_shippable_gift_card.expiry_date is None
sent_to_customer_event = GiftCardEvent.objects.get(
gift_card=non_shippable_gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER
@@ -232,7 +235,73 @@ def test_gift_cards_create(
)
assert shippable_event.user == staff_user
assert shippable_event.app is None
- assert shippable_event.parameters == {"order_id": order.id}
+ assert shippable_event.parameters == {"order_id": order.id, "expiry_date": None}
+
+ send_notification_mock.assert_called_once_with(
+ staff_user, None, user_email, non_shippable_gift_card, manager
+ )
+
+
+@patch("saleor.giftcard.utils.send_gift_card_notification")
+def test_gift_cards_create_expiry_date_set(
+ send_notification_mock,
+ order,
+ gift_card_shippable_order_line,
+ gift_card_non_shippable_order_line,
+ site_settings,
+ staff_user,
+):
+ # given
+ manager = get_plugins_manager()
+ site_settings.gift_card_expiry_type = GiftCardSettingsExpiryType.EXPIRY_PERIOD
+ site_settings.gift_card_expiry_period_type = TimePeriodType.WEEK
+ site_settings.gift_card_expiry_period = 20
+ site_settings.save(
+ update_fields=[
+ "gift_card_expiry_type",
+ "gift_card_expiry_period_type",
+ "gift_card_expiry_period",
+ ]
+ )
+ order_lines = [gift_card_non_shippable_order_line]
+ quantities = {
+ gift_card_shippable_order_line.pk: 1,
+ gift_card_non_shippable_order_line.pk: 1,
+ }
+ user_email = order.user_email
+
+ # when
+ gift_cards = gift_cards_create(
+ order, order_lines, quantities, site_settings, staff_user, None, manager
+ )
+
+ # then
+ assert len(gift_cards) == len(order_lines)
+
+ non_shippable_gift_card = gift_cards[0]
+ non_shippable_price = gift_card_non_shippable_order_line.total_price_gross
+ assert non_shippable_gift_card.initial_balance == non_shippable_price
+ assert non_shippable_gift_card.current_balance == non_shippable_price
+ assert non_shippable_gift_card.created_by == order.user
+ assert non_shippable_gift_card.created_by_email == user_email
+ assert non_shippable_gift_card.expiry_date
+
+ sent_to_customer_event = GiftCardEvent.objects.get(
+ gift_card=non_shippable_gift_card, type=GiftCardEvents.SENT_TO_CUSTOMER
+ )
+ assert sent_to_customer_event.user == staff_user
+ assert sent_to_customer_event.app is None
+ assert sent_to_customer_event.parameters == {"email": user_email}
+
+ shippable_event = GiftCardEvent.objects.get(
+ gift_card=non_shippable_gift_card, type=GiftCardEvents.BOUGHT
+ )
+ assert shippable_event.user == staff_user
+ assert shippable_event.app is None
+ assert shippable_event.parameters == {
+ "order_id": order.id,
+ "expiry_date": non_shippable_gift_card.expiry_date.isoformat(),
+ }
send_notification_mock.assert_called_once_with(
staff_user, None, user_email, non_shippable_gift_card, manager
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index ab5a1098cd..85804d92dd 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -6,7 +6,8 @@ from django.utils import timezone
from ..checkout.models import Checkout
from ..core.utils.promo_code import InvalidPromoCode, generate_promo_code
-from . import GiftCardExpiryType, events
+from ..site import GiftCardSettingsExpiryType
+from . import events
from .models import GiftCard
from .notifications import send_gift_card_notification
@@ -64,19 +65,6 @@ def activate_gift_card(gift_card: GiftCard):
gift_card.save(update_fields=["is_active"])
-def calculate_expiry_date(gift_card: GiftCard):
- """Calculate gift card expiry date for gift card with expiry period settings.
-
- Return None for gift card with different expiry settings.
- """
- today = timezone.now().date()
- expiry_date = None
- if gift_card.expiry_type == GiftCardExpiryType.EXPIRY_PERIOD:
- time_delta = {f"{gift_card.expiry_period_type}s": gift_card.expiry_period}
- expiry_date = today + relativedelta(**time_delta) # type: ignore
- return expiry_date
-
-
def gift_cards_create(
order: "Order",
gift_card_lines: Iterable["OrderLine"],
@@ -91,6 +79,7 @@ def gift_cards_create(
user_email = order.user_email
gift_cards = []
non_shippable_gift_cards = []
+ expiry_date = calculate_expiry_date(settings)
for order_line in gift_card_lines:
price = order_line.unit_price_gross
line_gift_cards = [
@@ -101,9 +90,7 @@ def gift_cards_create(
created_by=customer_user,
created_by_email=user_email,
product=order_line.variant.product if order_line.variant else None,
- expiry_type=settings.gift_card_expiry_type,
- expiry_period_type=settings.gift_card_expiry_period_type,
- expiry_period=settings.gift_card_expiry_period,
+ expiry_date=expiry_date,
)
for _ in range(quantities[order_line.pk])
]
@@ -121,6 +108,17 @@ def gift_cards_create(
return gift_cards
+def calculate_expiry_date(settings):
+ """Calculate expiry date based on gift card settings."""
+ today = timezone.now().date()
+ expiry_date = None
+ if settings.gift_card_expiry_type == GiftCardSettingsExpiryType.EXPIRY_PERIOD:
+ expiry_period_type = settings.gift_card_expiry_period_type
+ time_delta = {f"{expiry_period_type}s": settings.gift_card_expiry_period}
+ expiry_date = today + relativedelta(**time_delta) # type: ignore
+ return expiry_date
+
+
def send_gift_cards_to_customer(
gift_cards: Iterable[GiftCard],
user_email: str,
diff --git a/saleor/graphql/giftcard/enums.py b/saleor/graphql/giftcard/enums.py
index 83fbabf24d..98a31bdff9 100644
--- a/saleor/graphql/giftcard/enums.py
+++ b/saleor/graphql/giftcard/enums.py
@@ -1,5 +1,4 @@
-from ...giftcard import GiftCardEvents, GiftCardExpiryType
+from ...giftcard import GiftCardEvents
from ..core.enums import to_enum
-GiftCardExpiryTypeEnum = to_enum(GiftCardExpiryType)
GiftCardEventsEnum = to_enum(GiftCardEvents)
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index 0042f99cf4..93df49160b 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -7,30 +7,22 @@ from django.core.validators import validate_email
from ...core.permissions import GiftcardPermissions
from ...core.utils.promo_code import generate_promo_code
from ...core.utils.validators import date_passed, user_is_valid
-from ...giftcard import GiftCardExpiryType, events, models
+from ...giftcard import events, models
from ...giftcard.error_codes import GiftCardErrorCode
from ...giftcard.notifications import send_gift_card_notification
from ...giftcard.utils import activate_gift_card, deactivate_gift_card
from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.scalars import PositiveDecimal
-from ..core.types.common import GiftCardError, PriceInput, TimePeriodInputType
+from ..core.types.common import GiftCardError, PriceInput
from ..core.utils import validate_required_string_field
from ..core.validators import validate_price_precision
-from .enums import GiftCardExpiryTypeEnum
from .types import GiftCard, GiftCardEvent
-class GiftCardExpirySettingsInput(graphene.InputObjectType):
- expiry_type = GiftCardExpiryTypeEnum(
- description="The gift card expiry type.", required=True
- )
- expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")
- expiry_period = TimePeriodInputType(description="The gift card expiry period.")
-
-
class GiftCardInput(graphene.InputObjectType):
tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")
+ expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")
# DEPRECATED
start_date = graphene.types.datetime.Date(
@@ -54,9 +46,6 @@ class GiftCardCreateInput(GiftCardInput):
required=False,
description="Email of the customer to whom gift card will be sent.",
)
- expiry_settings = GiftCardExpirySettingsInput(
- description=f"{ADDED_IN_31} The gift card expiry settings.", required=True
- )
code = graphene.String(
required=False,
description=(
@@ -71,9 +60,6 @@ class GiftCardUpdateInput(GiftCardInput):
balance_amount = PositiveDecimal(
description=f"{ADDED_IN_31} The gift card balance amount.", required=False
)
- expiry_settings = GiftCardExpirySettingsInput(
- description=f"{ADDED_IN_31} The gift card expiry settings.", required=False
- )
class GiftCardCreate(ModelMutation):
@@ -98,7 +84,7 @@ class GiftCardCreate(ModelMutation):
cleaned_input["code"] = generate_promo_code()
cls.set_created_by_user(cleaned_input, info)
- cls.clean_expiry_settings(cleaned_input, instance)
+ cls.clean_expiry_date(cleaned_input, instance)
cls.clean_balance(cleaned_input, instance)
if email := data.get("user_email"):
@@ -125,60 +111,17 @@ class GiftCardCreate(ModelMutation):
cleaned_input["app"] = info.context.app
@staticmethod
- def clean_expiry_settings(cleaned_input, instance):
- expiry_settings = cleaned_input.pop("expiry_settings", None)
- if not expiry_settings:
- return
- type = expiry_settings["expiry_type"]
- cleaned_input["expiry_type"] = type
- cleaned_input["expiry_period"] = None
- cleaned_input["expiry_period_type"] = None
- cleaned_input["expiry_date"] = None
- if type == GiftCardExpiryType.EXPIRY_DATE:
- expiry_date = expiry_settings.get("expiry_date")
- if not expiry_date:
- raise ValidationError(
- {
- "expiry_date": ValidationError(
- "Expiry date is required for chosen expiry type.",
- code=GiftCardErrorCode.REQUIRED.value,
- )
- }
- )
- if date_passed(expiry_date):
- raise ValidationError(
- {
- "expiry_date": ValidationError(
- "Expiry date cannot be in the past.",
- code=GiftCardErrorCode.INVALID.value,
- )
- }
- )
- cleaned_input["expiry_date"] = expiry_date
- elif type == GiftCardExpiryType.EXPIRY_PERIOD:
- expiry_period = expiry_settings.get("expiry_period")
- if not expiry_period:
- raise ValidationError(
- {
- "expiry_period": ValidationError(
- "Expiry period settings are required for chosen "
- "expiry type.",
- code=GiftCardErrorCode.REQUIRED.value,
- )
- }
- )
- if instance.used_by_email:
- raise ValidationError(
- {
- "expiry_type": ValidationError(
- "The expiry type cannot be changed to the expiry period "
- "for the already used card.",
- code=GiftCardErrorCode.INVALID.value,
- )
- }
- )
- cleaned_input["expiry_period"] = expiry_period["amount"]
- cleaned_input["expiry_period_type"] = expiry_period["type"]
+ def clean_expiry_date(cleaned_input, instance):
+ expiry_date = cleaned_input.get("expiry_date")
+ if expiry_date and date_passed(expiry_date):
+ raise ValidationError(
+ {
+ "expiry_date": ValidationError(
+ "Expiry date cannot be in the past.",
+ code=GiftCardErrorCode.INVALID.value,
+ )
+ }
+ )
@staticmethod
def clean_balance(cleaned_input, instance):
@@ -281,8 +224,8 @@ class GiftCardUpdate(GiftCardCreate):
events.gift_card_balance_reset(
instance, old_instance, info.context.user, info.context.app
)
- if "expiry_type" in cleaned_input:
- events.gift_card_expiry_settings_updated(
+ if "expiry_date" in cleaned_input:
+ events.gift_card_expiry_date_updated(
instance, old_instance, info.context.user, info.context.app
)
diff --git a/saleor/graphql/giftcard/tests/benchmark/fixtures.py b/saleor/graphql/giftcard/tests/benchmark/fixtures.py
index 88366cd427..90d73a6ceb 100644
--- a/saleor/graphql/giftcard/tests/benchmark/fixtures.py
+++ b/saleor/graphql/giftcard/tests/benchmark/fixtures.py
@@ -3,7 +3,7 @@ import secrets
import pytest
from prices import Money
-from .....giftcard import GiftCardEvents, GiftCardExpiryType
+from .....giftcard import GiftCardEvents
from .....giftcard.models import GiftCard, GiftCardEvent
GIFT_CARD_COUNT_IN_BENCHMARKS = 20
@@ -23,7 +23,6 @@ def gift_cards_for_benchmarks(
created_by_email=customer_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
- expiry_type=GiftCardExpiryType.NEVER_EXPIRE,
tag="test-tag",
)
for _ in range(GIFT_CARD_COUNT_IN_BENCHMARKS)
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 61fb4cb300..893a90ce55 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py
@@ -5,27 +5,21 @@ import pytest
from .....giftcard.models import GiftCard
from ....tests.utils import get_graphql_content
-from ...enums import GiftCardExpiryTypeEnum
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
$balance: PriceInput!, $userEmail: String, $tag: String,
- $expirySettings: GiftCardExpirySettingsInput!, $note: String
+ $note: String, $expiryDate: Date
){
giftCardCreate(input: {
balance: $balance, userEmail: $userEmail, tag: $tag,
- expirySettings: $expirySettings, note: $note }) {
+ expiryDate: $expiryDate, note: $note }) {
giftCard {
id
code
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -102,7 +96,6 @@ def test_create_never_expiry_gift_card(
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -112,9 +105,7 @@ def test_create_never_expiry_gift_card(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
+ "expiry_date": None,
}
# when
@@ -146,11 +137,6 @@ UPDATE_GIFT_CARD_MUTATION = """
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -202,20 +188,8 @@ UPDATE_GIFT_CARD_MUTATION = """
currency
}
}
- expiry {
- expiryType
- oldExpiryType
- expiryPeriod {
- type
- amount
- }
- oldExpiryPeriod {
- type
- amount
- }
- expiryDate
- oldExpiryDate
- }
+ expiryDate
+ oldExpiryDate
}
}
errors {
@@ -240,7 +214,6 @@ def test_update_gift_card(
):
# given
initial_balance = 100.0
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date.today() + timedelta(days=365)
tag = "new-gift-card-tag"
variables = {
@@ -248,10 +221,7 @@ def test_update_gift_card(
"input": {
"balanceAmount": initial_balance,
"tag": tag,
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "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 12530aeb53..600299af1e 100644
--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py
+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py
@@ -38,20 +38,8 @@ FRAGMENT_EVENTS = """
currency
}
}
- expiry {
- expiryType
- oldExpiryType
- expiryPeriod {
- type
- amount
- }
- oldExpiryPeriod {
- type
- amount
- }
- expiryDate
- oldExpiryDate
- }
+ expiryDate
+ oldExpiryDate
}
"""
@@ -64,11 +52,6 @@ FRAGMENT_GIFT_CARD_DETAILS = (
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
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 dd7cfeaabe..42e69791ac 100644
--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py
@@ -1,18 +1,17 @@
from datetime import date
from ....tests.utils import get_graphql_content
-from ...enums import GiftCardExpiryTypeEnum
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
- $startDate: Date, $endDate: Date, $expirySettings: GiftCardExpirySettingsInput!
+ $startDate: Date, $endDate: Date, $expiryDate: Date
$balance: PriceInput!, $userEmail: String
){
giftCardCreate(input: {
startDate: $startDate,
endDate: $endDate,
balance: $balance, userEmail: $userEmail,
- expirySettings: $expirySettings
+ expiryDate: $expiryDate
}) {
giftCard {
id
@@ -22,11 +21,6 @@ CREATE_GIFT_CARD_MUTATION = """
startDate
endDate
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -61,7 +55,6 @@ def test_create_never_expiry_gift_card(
):
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
start_date = date(day=1, month=1, year=2018)
end_date = date(day=1, month=1, year=2019)
@@ -74,9 +67,6 @@ def test_create_never_expiry_gift_card(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
}
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py
index 5f69f1091b..8712f2c123 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py
@@ -20,15 +20,13 @@ MUTATION_GIFT_CARD_BULK_ACTIVATE = """
def test_gift_card_bulk_activate_by_staff(
staff_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
gift_card.is_active = False
- gift_card_expiry_period.is_active = False
gift_card_expiry_date.is_active = True
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
GiftCard.objects.bulk_update(gift_cards, ["is_active"])
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
@@ -47,10 +45,9 @@ def test_gift_card_bulk_activate_by_staff(
assert data["count"] == len(ids)
events = GiftCardEvent.objects.all()
- assert events.count() == 2
+ assert events.count() == 1
assert {event.gift_card_id for event in events} == {
gift_card.id,
- gift_card_expiry_period.id,
}
assert {event.type for event in events} == {GiftCardEvents.ACTIVATED}
@@ -58,15 +55,13 @@ def test_gift_card_bulk_activate_by_staff(
def test_gift_card_bulk_activate_by_app(
app_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
gift_card.is_active = False
- gift_card_expiry_period.is_active = False
gift_card_expiry_date.is_active = False
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
GiftCard.objects.bulk_update(gift_cards, ["is_active"])
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
@@ -93,12 +88,11 @@ def test_gift_card_bulk_activate_by_app(
def test_gift_card_bulk_activate_all_cards_already_active(
staff_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
GiftCard.objects.bulk_update(gift_cards, ["is_active"])
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
@@ -121,12 +115,12 @@ def test_gift_card_bulk_activate_all_cards_already_active(
def test_gift_card_bulk_activate_by_customer(
- api_client, gift_card, gift_card_expiry_period
+ api_client, gift_card, gift_card_expiry_date
):
# given
gift_card.is_active = False
- gift_card_expiry_period.is_active = False
- gift_cards = [gift_card, gift_card_expiry_period]
+ gift_card_expiry_date.is_active = False
+ gift_cards = [gift_card, gift_card_expiry_date]
GiftCard.objects.bulk_update(gift_cards, ["is_active"])
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_deactivate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_deactivate.py
index d18ee34bbe..2374d19438 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_deactivate.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_deactivate.py
@@ -20,12 +20,11 @@ MUTATION_GIFT_CARD_BULK_DEACTIVATE = """
def test_gift_card_bulk_deactivate_by_staff(
staff_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
variables = {"ids": ids}
@@ -45,15 +44,14 @@ def test_gift_card_bulk_deactivate_by_staff(
GiftCard.objects.filter(
id__in=[card.id for card in gift_cards], is_active=False
).count()
- == 3
+ == 2
)
assert data["count"] == len(ids)
events = GiftCardEvent.objects.all()
- assert events.count() == 3
+ assert events.count() == 2
assert {event.gift_card_id for event in events} == {
gift_card.id,
- gift_card_expiry_period.id,
gift_card_expiry_date.id,
}
assert {event.type for event in events} == {GiftCardEvents.DEACTIVATED}
@@ -62,12 +60,11 @@ def test_gift_card_bulk_deactivate_by_staff(
def test_gift_card_bulk_deactivate_by_app(
app_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
variables = {"ids": ids}
@@ -87,7 +84,7 @@ def test_gift_card_bulk_deactivate_by_app(
GiftCard.objects.filter(
id__in=[card.id for card in gift_cards], is_active=False
).count()
- == 3
+ == 2
)
assert data["count"] == len(ids)
@@ -100,12 +97,11 @@ def test_gift_card_bulk_deactivate_by_app(
def test_gift_card_bulk_deactivate_all_cards_already_inactive(
staff_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
permission_manage_gift_card,
):
# given
- gift_cards = [gift_card, gift_card_expiry_period, gift_card_expiry_date]
+ gift_cards = [gift_card, gift_card_expiry_date]
for card in gift_cards:
card.is_active = False
GiftCard.objects.bulk_update(gift_cards, ["is_active"])
@@ -130,10 +126,10 @@ def test_gift_card_bulk_deactivate_all_cards_already_inactive(
def test_gift_card_bulk_deactivate_by_customer(
- api_client, gift_card, gift_card_expiry_period
+ api_client, gift_card, gift_card_expiry_date
):
# given
- gift_cards = [gift_card, gift_card_expiry_period]
+ gift_cards = [gift_card, gift_card_expiry_date]
ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]
variables = {"ids": ids}
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_delete.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_delete.py
index e514c894d4..bce43df9bd 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_delete.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_delete.py
@@ -21,11 +21,10 @@ def test_gift_card_bulk_delete_by_staff(
staff_api_client,
permission_manage_gift_card,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
):
# given
- gift_card_pks = [gift_card.pk, gift_card_expiry_period.pk, gift_card_expiry_date.pk]
+ gift_card_pks = [gift_card.pk, gift_card_expiry_date.pk]
ids = [graphene.Node.to_global_id("GiftCard", pk) for pk in gift_card_pks]
variables = {"ids": ids}
@@ -49,11 +48,10 @@ def test_gift_card_bulk_delete_by_app(
app_api_client,
permission_manage_gift_card,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
):
# given
- gift_card_pks = [gift_card.pk, gift_card_expiry_period.pk, gift_card_expiry_date.pk]
+ gift_card_pks = [gift_card.pk, gift_card_expiry_date.pk]
ids = [graphene.Node.to_global_id("GiftCard", pk) for pk in gift_card_pks]
variables = {"ids": ids}
@@ -74,10 +72,10 @@ def test_gift_card_bulk_delete_by_app(
def test_gift_card_bulk_delete_by_customer(
- app_api_client, gift_card, gift_card_expiry_period, gift_card_expiry_date
+ app_api_client, gift_card, gift_card_expiry_date
):
# given
- gift_card_pks = [gift_card.pk, gift_card_expiry_period.pk, gift_card_expiry_date.pk]
+ gift_card_pks = [gift_card.pk, gift_card_expiry_date.pk]
ids = [graphene.Node.to_global_id("GiftCard", pk) for pk in gift_card_pks]
variables = {"ids": ids}
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 d2ba9c673e..fc285f44ac 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -2,29 +2,22 @@ from datetime import date, timedelta
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
-from ....core.enums import TimePeriodTypeEnum
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import GiftCardExpiryTypeEnum
CREATE_GIFT_CARD_MUTATION = """
mutation giftCardCreate(
$balance: PriceInput!, $userEmail: String, $tag: String,
- $expirySettings: GiftCardExpirySettingsInput!, $note: String
+ $expiryDate: Date, $note: String
){
giftCardCreate(input: {
balance: $balance, userEmail: $userEmail, tag: $tag,
- expirySettings: $expirySettings, note: $note }) {
+ expiryDate: $expiryDate, note: $note }) {
giftCard {
id
code
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -98,7 +91,6 @@ def test_create_never_expiry_gift_card(
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -108,9 +100,6 @@ def test_create_never_expiry_gift_card(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
}
# when
@@ -132,9 +121,7 @@ def test_create_never_expiry_gift_card(
assert not errors
assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert not data["expiryDate"]
- assert not data["expiryPeriod"]
assert data["tag"] == tag
assert data["createdBy"]["email"] == staff_api_client.user.email
assert data["createdByEmail"] == staff_api_client.user.email
@@ -173,7 +160,6 @@ def test_create_gift_card_by_app(
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -183,10 +169,7 @@ def test_create_gift_card_by_app(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": None,
- },
+ "expiryDate": None,
}
# when
@@ -204,9 +187,7 @@ def test_create_gift_card_by_app(
assert not errors
assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert not data["expiryDate"]
- assert not data["expiryPeriod"]
assert data["tag"] == tag
assert not data["createdBy"]
assert not data["createdByEmail"]
@@ -240,7 +221,6 @@ def test_create_gift_card_by_customer(api_client, customer_user):
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -250,10 +230,7 @@ def test_create_gift_card_by_customer(api_client, customer_user):
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": None,
- },
+ "expiryDate": None,
}
# when
@@ -270,7 +247,6 @@ def test_create_gift_card_no_premissions(staff_api_client):
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -279,10 +255,7 @@ def test_create_gift_card_no_premissions(staff_api_client):
},
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": None,
- },
+ "expiryDate": None,
}
# when
@@ -305,7 +278,6 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount(
# given
initial_balance = 10.123
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -315,9 +287,6 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
}
# when
@@ -351,7 +320,6 @@ def test_create_gift_card_with_malformed_email(
# given
initial_balance = 10
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -361,9 +329,6 @@ def test_create_gift_card_with_malformed_email(
"userEmail": "malformed",
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
}
# when
@@ -398,7 +363,6 @@ def test_create_gift_card_with_zero_balance_amount(
):
# given
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
tag = "gift-card-tag"
variables = {
"balance": {
@@ -408,9 +372,6 @@ def test_create_gift_card_with_zero_balance_amount(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
}
# when
@@ -445,7 +406,6 @@ def test_create_gift_card_with_expiry_date(
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date.today() + timedelta(days=365)
tag = "gift-card-tag"
variables = {
@@ -456,10 +416,7 @@ def test_create_gift_card_with_expiry_date(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
}
# when
@@ -481,9 +438,7 @@ def test_create_gift_card_with_expiry_date(
assert not errors
assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert data["expiryDate"] == date_value.isoformat()
- assert not data["expiryPeriod"]
assert len(data["events"]) == 2
created_event, sent_event = data["events"]
@@ -503,53 +458,6 @@ def test_create_gift_card_with_expiry_date(
assert not created_event["app"]
-def test_create_gift_card_with_expiry_date_type_date_not_given(
- staff_api_client,
- customer_user,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- initial_balance = 100
- currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
- tag = "gift-card-tag"
- variables = {
- "balance": {
- "amount": initial_balance,
- "currency": currency,
- },
- "userEmail": customer_user.email,
- "tag": tag,
- "note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
- }
-
- # when
- response = staff_api_client.post_graphql(
- CREATE_GIFT_CARD_MUTATION,
- variables,
- permissions=[
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- ],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["giftCardCreate"]["errors"]
- data = content["data"]["giftCardCreate"]["giftCard"]
-
- assert not data
- assert len(errors) == 1
- assert errors[0]["field"] == "expiryDate"
- assert errors[0]["code"] == GiftCardErrorCode.REQUIRED.name
-
-
def test_create_gift_card_with_expiry_date_type_date_in_past(
staff_api_client,
customer_user,
@@ -560,7 +468,6 @@ def test_create_gift_card_with_expiry_date_type_date_in_past(
# given
initial_balance = 100
currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date(1999, 1, 1)
tag = "gift-card-tag"
variables = {
@@ -571,10 +478,7 @@ def test_create_gift_card_with_expiry_date_type_date_in_past(
"userEmail": customer_user.email,
"tag": tag,
"note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
}
# when
@@ -597,176 +501,3 @@ def test_create_gift_card_with_expiry_date_type_date_in_past(
assert len(errors) == 1
assert errors[0]["field"] == "expiryDate"
assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
-
-
-def test_create_gift_card_with_expiry_period(
- staff_api_client,
- customer_user,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- initial_balance = 100
- currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
- tag = "gift-card-tag"
- period_amount = 10
- period_type = TimePeriodTypeEnum.MONTH.name
- variables = {
- "balance": {
- "amount": initial_balance,
- "currency": currency,
- },
- "userEmail": customer_user.email,
- "tag": tag,
- "note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryPeriod": {
- "type": period_type,
- "amount": period_amount,
- },
- },
- }
-
- # when
- response = staff_api_client.post_graphql(
- CREATE_GIFT_CARD_MUTATION,
- variables,
- permissions=[
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- ],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["giftCardCreate"]["errors"]
- data = content["data"]["giftCardCreate"]["giftCard"]
-
- assert not errors
- assert data["code"]
- assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
- assert not data["expiryDate"]
- assert data["expiryPeriod"]["amount"] == period_amount
- assert data["expiryPeriod"]["type"] == period_type
-
- assert len(data["events"]) == 2
- created_event, sent_event = data["events"]
-
- assert created_event["type"] == GiftCardEvents.ISSUED.upper()
- assert created_event["user"]["email"] == staff_api_client.user.email
- assert not created_event["app"]
- assert created_event["balance"]["initialBalance"]["amount"] == initial_balance
- assert created_event["balance"]["initialBalance"]["currency"] == currency
- assert created_event["balance"]["currentBalance"]["amount"] == initial_balance
- assert created_event["balance"]["currentBalance"]["currency"] == currency
- assert not created_event["balance"]["oldInitialBalance"]
- assert not created_event["balance"]["oldCurrentBalance"]
-
- assert sent_event["type"] == GiftCardEvents.SENT_TO_CUSTOMER.upper()
- assert sent_event["user"]["email"] == staff_api_client.user.email
- assert not created_event["app"]
-
-
-def test_create_gift_card_with_expiry_period_negative_amount(
- staff_api_client,
- customer_user,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- initial_balance = 100
- currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
- tag = "gift-card-tag"
- period_amount = -10
- period_type = TimePeriodTypeEnum.MONTH.name
- variables = {
- "balance": {
- "amount": initial_balance,
- "currency": currency,
- },
- "userEmail": customer_user.email,
- "tag": tag,
- "note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryPeriod": {
- "type": period_type,
- "amount": period_amount,
- },
- },
- }
-
- # when
- response = staff_api_client.post_graphql(
- CREATE_GIFT_CARD_MUTATION,
- variables,
- permissions=[
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- ],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["giftCardCreate"]["errors"]
- data = content["data"]["giftCardCreate"]["giftCard"]
-
- assert not data
- assert len(errors) == 1
- assert errors[0]["field"] == "expiryPeriod"
- assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
-
-
-def test_create_gift_card_with_expiry_period_type_period_data_not_given(
- staff_api_client,
- customer_user,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- initial_balance = 100
- currency = "USD"
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
- tag = "gift-card-tag"
- variables = {
- "balance": {
- "amount": initial_balance,
- "currency": currency,
- },
- "userEmail": customer_user.email,
- "tag": tag,
- "note": "This is gift card note that will be save in gift card event.",
- "expirySettings": {
- "expiryType": expiry_type,
- },
- }
-
- # when
- response = staff_api_client.post_graphql(
- CREATE_GIFT_CARD_MUTATION,
- variables,
- permissions=[
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
- ],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["giftCardCreate"]["errors"]
- data = content["data"]["giftCardCreate"]["giftCard"]
-
- assert not data
- assert len(errors) == 1
- assert errors[0]["field"] == "expiryPeriod"
- assert errors[0]["code"] == GiftCardErrorCode.REQUIRED.name
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 00e2b8b0bd..94c3bd226a 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
@@ -5,9 +5,7 @@ import pytest
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
-from ....core.enums import TimePeriodTypeEnum
from ....tests.utils import assert_no_permission, get_graphql_content
-from ...enums import GiftCardExpiryTypeEnum
UPDATE_GIFT_CARD_MUTATION = """
mutation giftCardUpdate(
@@ -16,15 +14,9 @@ UPDATE_GIFT_CARD_MUTATION = """
giftCardUpdate(id: $id, input: $input) {
giftCard {
id
- code
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -76,20 +68,8 @@ UPDATE_GIFT_CARD_MUTATION = """
currency
}
}
- expiry {
- expiryType
- oldExpiryType
- expiryPeriod {
- type
- amount
- }
- oldExpiryPeriod {
- type
- amount
- }
- expiryDate
- oldExpiryDate
- }
+ expiryDate
+ oldExpiryDate
}
}
errors {
@@ -112,11 +92,9 @@ 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_type = gift_card.expiry_type
initial_balance = 100.0
currency = gift_card.currency
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date.today() + timedelta(days=365)
tag = "new-gift-card-tag"
variables = {
@@ -124,10 +102,7 @@ def test_update_gift_card(
"input": {
"balanceAmount": initial_balance,
"tag": tag,
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
},
}
@@ -148,11 +123,8 @@ def test_update_gift_card(
data = content["data"]["giftCardUpdate"]["giftCard"]
assert not errors
- assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert data["expiryDate"] == date_value.isoformat()
- assert not data["expiryPeriod"]
assert data["tag"] == tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
@@ -190,23 +162,18 @@ def test_update_gift_card(
"currency": currency,
},
},
- "expiry": None,
+ "expiryDate": None,
+ "oldExpiryDate": None,
},
{
- "type": GiftCardEvents.EXPIRY_SETTINGS_UPDATED.upper(),
+ "type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
"user": {
"email": staff_api_client.user.email,
},
"app": None,
"balance": None,
- "expiry": {
- "expiryType": expiry_type.upper(),
- "oldExpiryType": old_type.upper(),
- "expiryPeriod": None,
- "oldExpiryPeriod": None,
- "expiryDate": date_value.isoformat(),
- "oldExpiryDate": None,
- },
+ "expiryDate": date_value.isoformat(),
+ "oldExpiryDate": None,
},
]
for event in data["events"]:
@@ -223,11 +190,9 @@ def test_update_gift_card_by_app(
# given
old_initial_balance = float(gift_card.initial_balance.amount)
old_current_balance = float(gift_card.current_balance.amount)
- old_type = gift_card.expiry_type
initial_balance = 100.0
currency = gift_card.currency
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date.today() + timedelta(days=365)
tag = "new-gift-card-tag"
variables = {
@@ -235,10 +200,7 @@ def test_update_gift_card_by_app(
"input": {
"balanceAmount": initial_balance,
"tag": tag,
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
},
}
@@ -259,11 +221,8 @@ def test_update_gift_card_by_app(
data = content["data"]["giftCardUpdate"]["giftCard"]
assert not errors
- assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert data["expiryDate"] == date_value.isoformat()
- assert not data["expiryPeriod"]
assert data["tag"] == tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
@@ -299,21 +258,16 @@ def test_update_gift_card_by_app(
"currency": currency,
},
},
- "expiry": None,
+ "expiryDate": None,
+ "oldExpiryDate": None,
},
{
- "type": GiftCardEvents.EXPIRY_SETTINGS_UPDATED.upper(),
+ "type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
"user": None,
"app": {"name": app_api_client.app.name},
"balance": None,
- "expiry": {
- "expiryType": expiry_type.upper(),
- "oldExpiryType": old_type.upper(),
- "expiryPeriod": None,
- "oldExpiryPeriod": None,
- "expiryDate": date_value.isoformat(),
- "oldExpiryDate": None,
- },
+ "expiryDate": date_value.isoformat(),
+ "oldExpiryDate": None,
},
]
for event in data["events"]:
@@ -380,9 +334,7 @@ def test_update_gift_card_balance(
data = content["data"]["giftCardUpdate"]["giftCard"]
assert not errors
- assert data["expiryType"] == gift_card.expiry_type.upper()
assert not data["expiryDate"]
- assert not data["expiryPeriod"]
assert data["tag"] == gift_card.tag
assert data["isActive"]
assert data["initialBalance"]["amount"] == initial_balance
@@ -413,12 +365,13 @@ def test_update_gift_card_balance(
"currency": currency,
},
},
- "expiry": None,
+ "expiryDate": None,
+ "oldExpiryDate": None,
}
assert expected_event == data["events"][0]
-def test_update_gift_card_change_to_expiry_period(
+def test_update_gift_card_change_to_never_expire(
staff_api_client,
gift_card_expiry_date,
permission_manage_gift_card,
@@ -427,93 +380,12 @@ def test_update_gift_card_change_to_expiry_period(
):
# given
gift_card = gift_card_expiry_date
- old_type = gift_card.expiry_type
old_expiry_date = gift_card.expiry_date
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
- expiry_period = 2
- expiry_period_type = TimePeriodTypeEnum.YEAR.name
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": None,
- "expiryPeriod": {
- "type": expiry_period_type,
- "amount": expiry_period,
- },
- },
- },
- }
-
- # 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 errors
- assert data["code"]
- assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
- assert not data["expiryDate"]
- assert data["expiryPeriod"]["amount"] == expiry_period
- assert data["expiryPeriod"]["type"] == expiry_period_type
- assert data["tag"] == gift_card.tag
- assert data["createdBy"]["email"] == gift_card.created_by.email
- assert data["createdByEmail"] == gift_card.created_by_email
-
- assert len(data["events"]) == 1
- expected_event = {
- "type": GiftCardEvents.EXPIRY_SETTINGS_UPDATED.upper(),
- "user": {
- "email": staff_api_client.user.email,
- },
- "app": None,
- "balance": None,
- "expiry": {
- "expiryType": expiry_type.upper(),
- "oldExpiryType": old_type.upper(),
- "expiryPeriod": {"amount": expiry_period, "type": expiry_period_type},
- "oldExpiryPeriod": None,
"expiryDate": None,
- "oldExpiryDate": old_expiry_date.isoformat(),
- },
- }
- assert expected_event == data["events"][0]
-
-
-def test_update_gift_card_change_to_never_expire(
- staff_api_client,
- gift_card_expiry_period,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- gift_card = gift_card_expiry_period
- old_type = gift_card.expiry_type
- old_expiry_period_type = gift_card.expiry_period_type
- old_expiry_period = gift_card.expiry_period
-
- expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
- variables = {
- "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
- "input": {
- "expirySettings": {
- "expiryType": expiry_type,
- },
},
}
@@ -534,57 +406,41 @@ def test_update_gift_card_change_to_never_expire(
data = content["data"]["giftCardUpdate"]["giftCard"]
assert not errors
- assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert not data["expiryDate"]
- assert not data["expiryPeriod"]
assert data["tag"] == gift_card.tag
assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["createdByEmail"] == gift_card.created_by_email
assert len(data["events"]) == 1
expected_event = {
- "type": GiftCardEvents.EXPIRY_SETTINGS_UPDATED.upper(),
+ "type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),
"user": {
"email": staff_api_client.user.email,
},
"app": None,
"balance": None,
- "expiry": {
- "expiryType": expiry_type.upper(),
- "oldExpiryType": old_type.upper(),
- "oldExpiryPeriod": {
- "amount": old_expiry_period,
- "type": old_expiry_period_type.upper(),
- },
- "expiryPeriod": None,
- "expiryDate": None,
- "oldExpiryDate": None,
- },
+ "expiryDate": None,
+ "oldExpiryDate": old_expiry_date.isoformat(),
}
assert expected_event == data["events"][0]
def test_update_used_gift_card_to_expiry_date(
staff_api_client,
- gift_card_expiry_period,
+ gift_card_used,
permission_manage_gift_card,
permission_manage_users,
permission_manage_apps,
):
# given
- gift_card = gift_card_expiry_period
+ gift_card = gift_card_used
date_value = date.today() + timedelta(days=365)
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
},
}
@@ -605,13 +461,15 @@ def test_update_used_gift_card_to_expiry_date(
data = content["data"]["giftCardUpdate"]["giftCard"]
assert not errors
- assert data["code"]
assert data["displayCode"]
- assert data["expiryType"] == expiry_type.upper()
assert data["expiryDate"] == date_value.isoformat()
+ assert len(data["events"]) == 1
+ event = data["events"][0]
+ assert event["expiryDate"] == date_value.isoformat()
+ assert event["oldExpiryDate"] is None
-def test_update_used_gift_card_to_expiry_period(
+def test_update_used_gift_card_to_never_expired(
staff_api_client,
gift_card_used,
permission_manage_gift_card,
@@ -621,65 +479,10 @@ def test_update_used_gift_card_to_expiry_period(
# given
gift_card = gift_card_used
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryPeriod": {
- "type": TimePeriodTypeEnum.DAY.name,
- "amount": 100,
- },
- },
- },
- }
-
- # 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"] == "expiryType"
- assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
-
-
-def test_update_gift_card_negative_period_amount(
- staff_api_client,
- gift_card_expiry_date,
- permission_manage_gift_card,
- permission_manage_users,
- permission_manage_apps,
-):
- # given
- gift_card = gift_card_expiry_date
-
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_PERIOD.name
- expiry_period = -10
- expiry_period_type = TimePeriodTypeEnum.YEAR.name
- variables = {
- "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
- "input": {
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryPeriod": {
- "type": expiry_period_type,
- "amount": expiry_period,
- },
- },
+ "expiryDate": None,
},
}
@@ -699,10 +502,9 @@ def test_update_gift_card_negative_period_amount(
errors = content["data"]["giftCardUpdate"]["errors"]
data = content["data"]["giftCardUpdate"]["giftCard"]
- assert not data
- assert len(errors) == 1
- assert errors[0]["field"] == "expiryPeriod"
- assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
+ assert not errors
+ assert data["displayCode"]
+ assert data["expiryDate"] is None
def test_update_gift_card_date_in_past(
@@ -713,15 +515,11 @@ def test_update_gift_card_date_in_past(
permission_manage_apps,
):
# given
- expiry_type = GiftCardExpiryTypeEnum.EXPIRY_DATE.name
date_value = date.today() - timedelta(days=365)
variables = {
"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
"input": {
- "expirySettings": {
- "expiryType": expiry_type,
- "expiryDate": date_value,
- },
+ "expiryDate": date_value,
},
}
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
index 9196a9b74d..be2c8a1cbf 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
@@ -1,4 +1,5 @@
-from datetime import timedelta
+import datetime
+from copy import deepcopy
import graphene
from django.utils import timezone
@@ -19,11 +20,6 @@ QUERY_GIFT_CARD_BY_ID = """
displayCode
isActive
expiryDate
- expiryType
- expiryPeriod {
- amount
- type
- }
tag
created
lastUsedOn
@@ -85,8 +81,6 @@ 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["expiryType"] == gift_card.expiry_type.upper()
- assert data["expiryPeriod"] is None
assert data["tag"] == gift_card.tag
assert data["created"] == gift_card.created.isoformat()
assert data["lastUsedOn"] == gift_card.last_used_on
@@ -117,7 +111,7 @@ def test_query_gift_card_no_permissions(staff_api_client, gift_card):
def test_query_gift_card_by_app(
app_api_client,
- gift_card_expiry_period,
+ gift_card,
permission_manage_gift_card,
permission_manage_users,
permission_manage_apps,
@@ -126,10 +120,10 @@ def test_query_gift_card_by_app(
query = QUERY_GIFT_CARD_BY_ID
app = app_api_client.app
- gift_card_expiry_period.app = app
- gift_card_expiry_period.save(update_fields=["app"])
+ gift_card.app = app
+ gift_card.save(update_fields=["app"])
- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_expiry_period.pk)
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
variables = {"id": gift_card_id}
# when
@@ -146,39 +140,21 @@ def test_query_gift_card_by_app(
content = get_graphql_content(response)
data = content["data"]["giftCard"]
assert data["id"] == gift_card_id
- assert data["code"] == gift_card_expiry_period.code
- assert data["displayCode"] == gift_card_expiry_period.display_code
- assert data["isActive"] == gift_card_expiry_period.is_active
+ assert data["code"] == gift_card.code
+ assert data["displayCode"] == gift_card.display_code
+ assert data["isActive"] == gift_card.is_active
assert data["expiryDate"] is None
- assert data["expiryType"] == gift_card_expiry_period.expiry_type.upper()
- assert data["expiryPeriod"]["amount"] == gift_card_expiry_period.expiry_period
- assert (
- data["expiryPeriod"]["type"]
- == gift_card_expiry_period.expiry_period_type.upper()
- )
- assert data["tag"] == gift_card_expiry_period.tag
- assert data["created"] == gift_card_expiry_period.created.isoformat()
- assert data["lastUsedOn"] == gift_card_expiry_period.last_used_on
- assert (
- data["initialBalance"]["currency"]
- == gift_card_expiry_period.initial_balance.currency
- )
- assert (
- data["initialBalance"]["amount"]
- == gift_card_expiry_period.initial_balance.amount
- )
- assert (
- data["currentBalance"]["currency"]
- == gift_card_expiry_period.current_balance.currency
- )
- assert (
- data["currentBalance"]["amount"]
- == gift_card_expiry_period.current_balance.amount
- )
- assert data["createdBy"]["email"] == gift_card_expiry_period.created_by.email
+ 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
+ assert data["initialBalance"]["amount"] == gift_card.initial_balance.amount
+ assert data["currentBalance"]["currency"] == gift_card.current_balance.currency
+ assert data["currentBalance"]["amount"] == gift_card.current_balance.amount
+ assert data["createdBy"]["email"] == gift_card.created_by.email
assert data["usedBy"] is None
- assert data["createdByEmail"] == gift_card_expiry_period.created_by_email
- assert data["usedByEmail"] == gift_card_expiry_period.used_by_email
+ assert data["createdByEmail"] == gift_card.created_by_email
+ assert data["usedByEmail"] == gift_card.used_by_email
assert data["product"] is None
assert data["app"]["name"] == app.name
@@ -228,8 +204,6 @@ def test_query_gift_card_with_expiry_date(
assert data["code"] == gift_card_expiry_date.code
assert data["displayCode"] == gift_card_expiry_date.display_code
assert data["expiryDate"] == gift_card_expiry_date.expiry_date.isoformat()
- assert data["expiryType"] == gift_card_expiry_date.expiry_type.upper()
- assert data["expiryPeriod"] is None
def test_query_gift_card_by_customer(
@@ -423,20 +397,8 @@ QUERY_GIFT_CARD_EVENTS = """
currency
}
}
- expiry {
- expiryType
- oldExpiryType
- expiryPeriod {
- type
- amount
- }
- oldExpiryPeriod {
- type
- amount
- }
- expiryDate
- oldExpiryDate
- }
+ expiryDate
+ oldExpiryDate
}
}
}
@@ -491,7 +453,7 @@ def test_query_gift_card_events(
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]["expiry"] is None
+ assert events_data[0]["expiryDate"] is None
assert events_data[1]["id"] == graphene.Node.to_global_id(
"GiftCardEvent", gift_card_event.pk
@@ -539,44 +501,25 @@ def test_query_gift_card_events(
events_data[1]["balance"]["oldCurrentBalance"]["currency"]
== parameters["balance"]["currency"]
)
- assert (
- events_data[1]["expiry"]["expiryType"]
- == parameters["expiry"]["expiry_type"].upper()
- )
- assert (
- events_data[1]["expiry"]["oldExpiryType"]
- == parameters["expiry"]["old_expiry_type"].upper()
- )
- assert (
- events_data[1]["expiry"]["expiryDate"]
- == parameters["expiry"]["expiry_date"].isoformat()
- )
- assert events_data[1]["expiry"]["oldExpiryDate"] is None
- assert (
- events_data[1]["expiry"]["expiryPeriod"]["amount"]
- == parameters["expiry"]["expiry_period"]
- )
- assert (
- events_data[1]["expiry"]["expiryPeriod"]["type"]
- == parameters["expiry"]["expiry_period_type"].upper()
- )
- assert events_data[1]["expiry"]["oldExpiryPeriod"] is None
+ assert events_data[1]["expiryDate"] == parameters["expiry_date"].isoformat()
+ assert events_data[1]["oldExpiryDate"] == parameters["old_expiry_date"].isoformat()
def test_query_gift_card_expiry_date_set_event(
staff_api_client,
- gift_card_expiry_period,
+ gift_card,
staff_user,
permission_manage_gift_card,
permission_manage_apps,
):
# given
- expiry_date = timezone.now().date() + timedelta(days=400)
- expiry_data = [(gift_card_expiry_period.id, expiry_date)]
- events.gift_cards_expiry_date_set(expiry_data, staff_user, None)
- variables = {
- "id": graphene.Node.to_global_id("GiftCard", gift_card_expiry_period.pk)
- }
+ old = deepcopy(gift_card)
+ expiry_date = datetime.date(2050, 1, 1)
+ gift_card.expiry_date = expiry_date
+ gift_card.save(update_fields=["expiry_date"])
+
+ events.gift_card_expiry_date_updated(gift_card, old, staff_user, None)
+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}
# when
response = staff_api_client.post_graphql(
@@ -588,12 +531,13 @@ def test_query_gift_card_expiry_date_set_event(
# then
content = get_graphql_content(response)
events_data = content["data"]["giftCard"]["events"]
- assert len(events_data) == gift_card_expiry_period.events.count()
+ assert len(events_data) == gift_card.events.count()
event_data = events_data[0]
- assert event_data["expiry"]["expiryDate"] == expiry_date.isoformat()
+ assert event_data["expiryDate"] == expiry_date.isoformat()
+ assert event_data["oldExpiryDate"] is None
assert event_data["user"]["email"] == staff_user.email
assert event_data["app"] is None
- assert event_data["type"] == GiftCardEvents.EXPIRY_DATE_SET.upper()
+ assert event_data["type"] == GiftCardEvents.EXPIRY_DATE_UPDATED.upper()
assert event_data["balance"] is None
@@ -635,7 +579,7 @@ def test_query_gift_card_used_in_order_event(
assert event_data["balance"]["currentBalance"]["currency"] == gift_card.currency
assert event_data["balance"]["oldCurrentBalance"]["amount"] == previous_balance
assert event_data["balance"]["oldCurrentBalance"]["currency"] == gift_card.currency
- assert event_data["expiry"] is None
+ assert event_data["expiryDate"] is None
assert events_data[0]["user"] is None
assert events_data[0]["app"]["name"] == app.name
assert event_data["type"] == GiftCardEvents.USED_IN_ORDER.upper()
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py b/saleor/graphql/giftcard/tests/queries/test_gift_cards.py
index 30d62415ae..1c090c9441 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_cards.py
@@ -47,8 +47,8 @@ def test_query_gift_cards(
"filter_value, expected_gift_card_indexes",
[
("test-tag", [0]),
- ("another-tag", [1, 2]),
- ("tag", [0, 1, 2, 3]),
+ ("another-tag", [1]),
+ ("tag", [0, 1, 2]),
("not existing", []),
],
)
@@ -57,7 +57,6 @@ def test_query_filter_gift_cards(
expected_gift_card_indexes,
staff_api_client,
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
gift_card_used,
permission_manage_gift_card,
@@ -66,7 +65,6 @@ def test_query_filter_gift_cards(
query = QUERY_GIFT_CARDS
gift_cards = [
gift_card,
- gift_card_expiry_period,
gift_card_expiry_date,
gift_card_used,
]
diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.py
index 9c47440a58..40d8200855 100644
--- a/saleor/graphql/giftcard/types.py
+++ b/saleor/graphql/giftcard/types.py
@@ -1,6 +1,5 @@
import datetime
from decimal import Decimal
-from typing import Dict, Union
import graphene
import prices
@@ -16,14 +15,13 @@ from ..app.dataloaders import AppByIdLoader
from ..app.types import App
from ..core.connection import CountableDjangoObjectType
from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD
-from ..core.types.common import TimePeriod
from ..core.types.money import Money
from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
from ..product.dataloaders.products import ProductByIdLoader
from ..utils import get_user_or_app_from_context
from .dataloaders import GiftCardEventsByGiftCardIdLoader
-from .enums import GiftCardEventsEnum, GiftCardExpiryTypeEnum
+from .enums import GiftCardEventsEnum
class GiftCardEventBalance(graphene.ObjectType):
@@ -46,23 +44,6 @@ class GiftCardEventBalance(graphene.ObjectType):
)
-class GiftCardEventExpiry(graphene.ObjectType):
- expiry_type = GiftCardExpiryTypeEnum(description="The gift card expiry type.")
- expiry_period = graphene.Field(
- TimePeriod, description="The gift card expiry period.", required=False
- )
- expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")
- old_expiry_type = GiftCardExpiryTypeEnum(
- description="Previous gift card expiry type."
- )
- old_expiry_period = graphene.Field(
- TimePeriod, description="Previous gift card expiry period.", required=False
- )
- old_expiry_date = graphene.types.datetime.Date(
- description="Previous gift card expiry date."
- )
-
-
class GiftCardEvent(CountableDjangoObjectType):
date = graphene.types.datetime.DateTime(
description="Date when event happened at in ISO 8601 format."
@@ -86,8 +67,9 @@ class GiftCardEvent(CountableDjangoObjectType):
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 = graphene.Field(
- GiftCardEventExpiry, description="The gift card expiry settings."
+ expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")
+ old_expiry_date = graphene.types.datetime.Date(
+ description="Previous gift card expiry date."
)
class Meta:
@@ -173,33 +155,17 @@ class GiftCardEvent(CountableDjangoObjectType):
return GiftCardEventBalance(**balance_data)
@staticmethod
- @traced_resolver
- def resolve_expiry(root: models.GiftCardEvent, _info):
- expiry = root.parameters.get("expiry")
- if expiry is None:
- return None
+ def resolve_expiry_date(root: models.GiftCardEvent, _info):
+ expiry_date = root.parameters.get("expiry_date")
+ return (
+ datetime.datetime.strptime(expiry_date, "%Y-%m-%d") if expiry_date else None
+ )
- expiry_data: Dict[str, Union[TimePeriod, datetime.datetime, None]] = {}
- for period_field in ["expiry_period", "old_expiry_period"]:
- expiry_data[period_field] = (
- TimePeriod(
- amount=expiry.get(period_field),
- type=expiry.get(f"{period_field}_type"),
- )
- if expiry.get(period_field)
- else None
- )
-
- for date_field in ["expiry_date", "old_expiry_date"]:
- date = expiry.get(date_field)
- expiry_data[date_field] = (
- datetime.datetime.strptime(date, "%Y-%m-%d") if date else None
- )
-
- return GiftCardEventExpiry(
- expiry_type=expiry.get("expiry_type"),
- old_expiry_type=expiry.get("old_expiry_type"),
- **expiry_data,
+ @staticmethod
+ def resolve_old_expiry_date(root: models.GiftCardEvent, _info):
+ expiry_date = root.parameters.get("old_expiry_date")
+ return (
+ datetime.datetime.strptime(expiry_date, "%Y-%m-%d") if expiry_date else None
)
@@ -240,17 +206,6 @@ class GiftCard(CountableDjangoObjectType):
App,
description=f"{ADDED_IN_31} App which created the gift card.",
)
- expiry_type = GiftCardExpiryTypeEnum(
- description=f"{ADDED_IN_31} The gift card expiry type.", required=True
- )
- expiry_period = graphene.Field(
- TimePeriod,
- description=f"{ADDED_IN_31} The gift card expiry period.",
- required=False,
- )
- expiry_date = graphene.types.datetime.Date(
- description=f"{ADDED_IN_31} The gift card expiry date."
- )
product = graphene.Field(
"saleor.graphql.product.types.products.Product",
description=f"{ADDED_IN_31} Related gift card product.",
@@ -291,7 +246,6 @@ class GiftCard(CountableDjangoObjectType):
"initial_balance",
"current_balance",
"expiry_date",
- "expiry_type",
"tag",
]
interfaces = [graphene.relay.Node, ObjectWithMetadata]
@@ -414,12 +368,6 @@ class GiftCard(CountableDjangoObjectType):
def resolve_events(root: models.GiftCard, _info):
return GiftCardEventsByGiftCardIdLoader(_info.context).load(root.id)
- @staticmethod
- def resolve_expiry_period(root: models.GiftCard, info):
- if root.expiry_period_type is None:
- return None
- return TimePeriod(amount=root.expiry_period, type=root.expiry_period_type)
-
# DEPRECATED
@staticmethod
def resolve_user(root: models.GiftCard, info):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e72828b5bb..27b5d3a6e9 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2230,7 +2230,6 @@ type GiftCard implements Node & ObjectWithMetadata {
code: String!
isActive: Boolean!
expiryDate: Date
- expiryType: GiftCardExpiryTypeEnum!
tag: String
created: DateTime!
lastUsedOn: DateTime
@@ -2245,7 +2244,6 @@ type GiftCard implements Node & ObjectWithMetadata {
createdByEmail: String
usedByEmail: String
app: App
- expiryPeriod: TimePeriod
product: Product
events: [GiftCardEvent!]!
user: User @deprecated(reason: "This field will be removed in Saleor 4.0. Use `createdBy` field instead.")
@@ -2303,11 +2301,11 @@ type GiftCardCreate {
input GiftCardCreateInput {
tag: String
+ expiryDate: Date
startDate: Date
endDate: Date
balance: PriceInput!
userEmail: String
- expirySettings: GiftCardExpirySettingsInput!
code: String
note: String
}
@@ -2352,7 +2350,8 @@ type GiftCardEvent implements Node {
tag: String
oldTag: String
balance: GiftCardEventBalance
- expiry: GiftCardEventExpiry
+ expiryDate: Date
+ oldExpiryDate: Date
}
type GiftCardEventBalance {
@@ -2362,15 +2361,6 @@ type GiftCardEventBalance {
oldCurrentBalance: Money
}
-type GiftCardEventExpiry {
- expiryType: GiftCardExpiryTypeEnum
- expiryPeriod: TimePeriod
- expiryDate: Date
- oldExpiryType: GiftCardExpiryTypeEnum
- oldExpiryPeriod: TimePeriod
- oldExpiryDate: Date
-}
-
enum GiftCardEventsEnum {
ISSUED
BOUGHT
@@ -2378,26 +2368,13 @@ enum GiftCardEventsEnum {
ACTIVATED
DEACTIVATED
BALANCE_RESET
- EXPIRY_SETTINGS_UPDATED
- EXPIRY_DATE_SET
+ EXPIRY_DATE_UPDATED
SENT_TO_CUSTOMER
RESENT
NOTE_ADDED
USED_IN_ORDER
}
-input GiftCardExpirySettingsInput {
- expiryType: GiftCardExpiryTypeEnum!
- expiryDate: Date
- expiryPeriod: TimePeriodInputType
-}
-
-enum GiftCardExpiryTypeEnum {
- NEVER_EXPIRE
- EXPIRY_PERIOD
- EXPIRY_DATE
-}
-
input GiftCardFilterInput {
tag: String
}
@@ -2452,10 +2429,10 @@ type GiftCardUpdate {
input GiftCardUpdateInput {
tag: String
+ expiryDate: Date
startDate: Date
endDate: Date
balanceAmount: PositiveDecimal
- expirySettings: GiftCardExpirySettingsInput
}
type Group implements Node {
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index be5be461a0..cf4831cabd 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -2,8 +2,6 @@ from decimal import Decimal
from unittest.mock import Mock
import pytest
-from dateutil.relativedelta import relativedelta
-from django.utils import timezone
from prices import Money, TaxedMoney
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -284,11 +282,11 @@ def test_add_variant_to_order(order, customer_user, variant):
def test_add_gift_cards_to_order(
- checkout_with_item, gift_card, gift_card_expiry_period, order, staff_user
+ checkout_with_item, gift_card, gift_card_expiry_date, order, staff_user
):
# given
checkout = checkout_with_item
- checkout.gift_cards.add(gift_card, gift_card_expiry_period)
+ checkout.gift_cards.add(gift_card, gift_card_expiry_date)
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
@@ -300,9 +298,9 @@ def test_add_gift_cards_to_order(
# then
gift_card.refresh_from_db()
- gift_card_expiry_period.refresh_from_db()
+ gift_card_expiry_date.refresh_from_db()
assert gift_card.current_balance_amount == 0
- assert gift_card_expiry_period.current_balance_amount == 0
+ assert gift_card_expiry_date.current_balance_amount == 0
gift_card_events = GiftCardEvent.objects.filter(gift_card_id=gift_card.id)
assert gift_card_events.count() == 1
@@ -319,12 +317,8 @@ def test_add_gift_cards_to_order(
"order_id": order.id,
}
- gift_card_expiry_period_events = GiftCardEvent.objects.filter(
- gift_card_id=gift_card_expiry_period.id
- )
- assert len(gift_card_expiry_period_events) == 2
- order_created_event = gift_card_expiry_period_events.get(
- type=GiftCardEvents.USED_IN_ORDER
+ order_created_event = GiftCardEvent.objects.get(
+ gift_card_id=gift_card_expiry_date.id
)
assert order_created_event.user == staff_user
assert order_created_event.app is None
@@ -336,13 +330,3 @@ def test_add_gift_cards_to_order(
},
"order_id": order.id,
}
- expiry_date_set_event = gift_card_expiry_period_events.get(
- type=GiftCardEvents.EXPIRY_DATE_SET
- )
- assert expiry_date_set_event.user == staff_user
- assert expiry_date_set_event.app is None
- assert expiry_date_set_event.parameters == {
- "expiry": {
- "expiry_date": (timezone.now().date() + relativedelta(years=2)).isoformat()
- }
- }
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index f2e9da2c10..b2b810f903 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -16,7 +16,6 @@ from ..discount.models import NotApplicable, OrderDiscount, Voucher, VoucherType
from ..discount.utils import get_products_voucher_discount, validate_voucher_in_order
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
-from ..giftcard.utils import calculate_expiry_date
from ..order import FulfillmentStatus, OrderLineData, OrderStatus
from ..order.models import Order, OrderLine
from ..product.utils.digital_products import get_default_digital_content_settings
@@ -32,8 +31,6 @@ from ..warehouse.models import Warehouse
from . import events
if TYPE_CHECKING:
- from datetime import date
-
from ..app.models import App
from ..checkout.fetch import CheckoutInfo
from ..plugins.manager import PluginsManager
@@ -416,7 +413,6 @@ def add_gift_cards_to_order(
):
order_gift_cards = []
gift_cards_to_update = []
- expiry_date_data: List[Tuple[int, "date"]] = []
balance_data: List[Tuple[GiftCard, float]] = []
used_by_user = checkout_info.user
used_by_email = checkout_info.get_customer_email()
@@ -426,10 +422,7 @@ def add_gift_cards_to_order(
update_gift_card_balance(gift_card, total_price_left, balance_data)
- # set user and expiry date value when gift card is used for the first time
- set_gift_card_user_and_expiry_date(
- gift_card, used_by_user, used_by_email, expiry_date_data
- )
+ set_gift_card_user(gift_card, used_by_user, used_by_email)
gift_card.last_used_on = timezone.now()
gift_cards_to_update.append(gift_card)
@@ -441,12 +434,8 @@ def add_gift_cards_to_order(
"used_by",
"used_by_email",
]
- if expiry_date_data:
- update_fields.append("expiry_date")
GiftCard.objects.bulk_update(gift_cards_to_update, update_fields)
gift_card_events.gift_cards_used_in_order(balance_data, order.id, user, app)
- if expiry_date_data:
- gift_card_events.gift_cards_expiry_date_set(expiry_date_data, user, app)
def update_gift_card_balance(
@@ -464,19 +453,15 @@ def update_gift_card_balance(
balance_data.append((gift_card, previous_balance.amount))
-def set_gift_card_user_and_expiry_date(
+def set_gift_card_user(
gift_card: GiftCard,
used_by_user: Optional[User],
used_by_email: str,
- expiry_date_data: List[Tuple[int, "date"]],
):
+ """Set user when the gift card is used for the first time."""
if gift_card.used_by_email is None:
gift_card.used_by = used_by_user
gift_card.used_by_email = used_by_email
- expiry_date = calculate_expiry_date(gift_card)
- if expiry_date is not None:
- gift_card.expiry_date = expiry_date
- expiry_date_data.append((gift_card.id, expiry_date))
def _update_allocations_for_line(
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 54148b2a83..8af9bf814e 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -54,7 +54,7 @@ from ..discount.models import (
VoucherCustomer,
VoucherTranslation,
)
-from ..giftcard import GiftCardEvents, GiftCardExpiryType
+from ..giftcard import GiftCardEvents
from ..giftcard.models import GiftCard, GiftCardEvent
from ..menu.models import Menu, MenuItem, MenuItemTranslation
from ..order import OrderLineData, OrderOrigin, OrderStatus
@@ -2809,26 +2809,10 @@ def gift_card(customer_user):
created_by_email=customer_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
- expiry_type=GiftCardExpiryType.NEVER_EXPIRE,
tag="test-tag",
)
-def gift_card_expiry_period(customer_user):
- return GiftCard.objects.create(
- code="expiry_period",
- created_by=customer_user,
- created_by_email=customer_user.email,
- initial_balance=Money(10, "USD"),
- current_balance=Money(10, "USD"),
- expiry_type=GiftCardExpiryType.EXPIRY_PERIOD,
- expiry_period_type=TimePeriodType.YEAR,
- expiry_period=2,
- tag="another-tag",
- )
-
-
@pytest.fixture
def gift_card_expiry_date(customer_user):
return GiftCard.objects.create(
@@ -2837,7 +2821,6 @@ def gift_card_expiry_date(customer_user):
created_by_email=customer_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
- expiry_type=GiftCardExpiryType.EXPIRY_DATE,
expiry_date=datetime.date.today() + datetime.timedelta(days=100),
tag="another-tag",
)
@@ -2853,7 +2836,6 @@ def gift_card_used(staff_user, customer_user):
used_by_email=customer_user.email,
initial_balance=Money(100, "USD"),
current_balance=Money(100, "USD"),
- expiry_type=GiftCardExpiryType.NEVER_EXPIRE,
tag="tag",
)
@@ -2866,9 +2848,6 @@ def gift_card_created_by_staff(staff_user):
created_by_email=staff_user.email,
initial_balance=Money(10, "USD"),
current_balance=Money(10, "USD"),
- expiry_type=GiftCardExpiryType.EXPIRY_PERIOD,
- expiry_period_type=TimePeriodType.YEAR,
- expiry_period=2,
tag="test-tag",
)
@@ -2888,13 +2867,8 @@ def gift_card_event(gift_card, order, app, staff_user):
"current_balance": 10,
"old_current_balance": 5,
},
- "expiry": {
- "expiry_type": GiftCardExpiryType.EXPIRY_PERIOD,
- "old_expiry_type": GiftCardExpiryType.EXPIRY_DATE,
- "expiry_period_type": TimePeriodType.MONTH,
- "expiry_period": 10,
- "expiry_date": datetime.date(2050, 1, 1),
- },
+ "expiry_date": datetime.date(2050, 1, 1),
+ "old_expiry_date": datetime.date(2010, 1, 1),
}
return GiftCardEvent.objects.create(
user=staff_user,