Skip to content

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

Resend gift card mutation

Tomasz Szymanskifecb13918457
diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.py
index 6d0e8e71b7..da30503354 100644
--- a/saleor/giftcard/events.py
+++ b/saleor/giftcard/events.py
@@ -43,6 +43,18 @@ def gift_card_sent(
)
+def gift_card_resent(
+ gift_card_id: int, user_id: Optional[int], app_id: Optional[int], email: str
+):
+ return GiftCardEvent.objects.create(
+ gift_card_id=gift_card_id,
+ user_id=user_id,
+ app_id=app_id,
+ type=GiftCardEvents.RESENT,
+ parameters={"email": email},
+ )
+
+
def gift_card_balance_reset(
gift_card: GiftCard,
old_gift_card: GiftCard,
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index d9160743a2..d9491427e9 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -2,6 +2,7 @@ from copy import deepcopy
import graphene
from django.core.exceptions import ValidationError
+from django.core.validators import validate_email
from ...core.permissions import GiftcardPermissions
from ...core.utils.promo_code import generate_promo_code
@@ -99,7 +100,18 @@ class GiftCardCreate(ModelMutation):
cls.clean_expiry_settings(cleaned_input, instance)
cls.clean_balance(cleaned_input, instance)
- # TODO: validate user email
+ if email := data.get("user_email"):
+ try:
+ validate_email(email)
+ except ValidationError:
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "Provided email is invalid.",
+ code=GiftCardErrorCode.INVALID.value,
+ )
+ }
+ )
return cleaned_input
@@ -208,12 +220,6 @@ class GiftCardCreate(ModelMutation):
user=info.context.user,
app=info.context.app,
)
- events.gift_card_sent(
- gift_card_id=instance.id,
- user_id=info.context.user.id if info.context.user else None,
- app_id=info.context.app.id if info.context.app else None,
- email=cleaned_input["user_email"],
- )
send_gift_card_notification(
cleaned_input.get("created_by"),
cleaned_input.get("app"),
@@ -221,6 +227,12 @@ class GiftCardCreate(ModelMutation):
instance,
info.context.plugins,
)
+ events.gift_card_sent(
+ gift_card_id=instance.id,
+ user_id=info.context.user.id if info.context.user else None,
+ app_id=info.context.app.id if info.context.app else None,
+ email=cleaned_input["user_email"],
+ )
class GiftCardUpdate(GiftCardCreate):
@@ -342,3 +354,73 @@ class GiftCardActivate(BaseMutation):
gift_card=gift_card, user=info.context.user, app=info.context.app
)
return GiftCardActivate(gift_card=gift_card)
+
+
+class GiftCardResendInput(graphene.InputObjectType):
+ id = graphene.ID(required=True, description="ID of a gift card to resend.")
+ email = graphene.String(
+ required=False, description="Email to which gift card should be send."
+ )
+
+
+class GiftCardResend(BaseMutation):
+ gift_card = graphene.Field(GiftCard, description="Gift card which has been sent.")
+
+ class Arguments:
+ input = GiftCardResendInput(
+ required=True, description="Fields required to resend a gift card."
+ )
+
+ class Meta:
+ description = "Resend a gift card."
+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)
+ error_type_class = GiftCardError
+ error_type_field = "gift_card_errors"
+
+ @classmethod
+ def clean_input(cls, data):
+ if email := data.get("email"):
+ try:
+ validate_email(email)
+ except ValidationError:
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "Provided email is invalid.",
+ code=GiftCardErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ @classmethod
+ def get_target_email(cls, data, gift_card):
+ return (
+ data.get("email") or gift_card.used_by_email or gift_card.created_by_email
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ data = data.get("input")
+ cls.clean_input(data)
+ gift_card_id = data["id"]
+ gift_card = cls.get_node_or_error(
+ info, gift_card_id, field="gift_card_id", only_type=GiftCard
+ )
+ target_email = cls.get_target_email(data, gift_card)
+ user = None
+ if user_is_valid(info.context.user):
+ user = info.context.user
+ send_gift_card_notification(
+ user,
+ info.context.app,
+ target_email,
+ gift_card,
+ info.context.plugins,
+ )
+ events.gift_card_resent(
+ gift_card_id=gift_card.id,
+ user_id=user.id if user else None,
+ app_id=info.context.app.id if info.context.app else None,
+ email=target_email,
+ )
+ return GiftCardResend(gift_card=gift_card)
diff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.py
index 51b0715db5..f7db8aa131 100644
--- a/saleor/graphql/giftcard/schema.py
+++ b/saleor/graphql/giftcard/schema.py
@@ -12,6 +12,7 @@ from .mutations import (
GiftCardCreate,
GiftCardDeactivate,
GiftCardDelete,
+ GiftCardResend,
GiftCardUpdate,
)
from .resolvers import resolve_gift_card, resolve_gift_cards
@@ -50,6 +51,7 @@ class GiftCardMutations(graphene.ObjectType):
gift_card_delete = GiftCardDelete.Field()
gift_card_deactivate = GiftCardDeactivate.Field()
gift_card_update = GiftCardUpdate.Field()
+ gift_card_resend = GiftCardResend.Field()
gift_card_bulk_delete = GiftCardBulkDelete.Field()
gift_card_bulk_activate = GiftCardBulkActivate.Field()
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 4e55147859..d2ba9c673e 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -342,6 +342,53 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount(
assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
+def test_create_gift_card_with_malformed_email(
+ staff_api_client,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+):
+ # given
+ initial_balance = 10
+ currency = "USD"
+ expiry_type = GiftCardExpiryTypeEnum.NEVER_EXPIRE.name
+ tag = "gift-card-tag"
+ variables = {
+ "balance": {
+ "amount": initial_balance,
+ "currency": currency,
+ },
+ "userEmail": "malformed",
+ "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)
+ data = content["data"]["giftCardCreate"]["giftCard"]
+ errors = content["data"]["giftCardCreate"]["errors"]
+
+ assert not data
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "email"
+ assert error["code"] == GiftCardErrorCode.INVALID.name
+
+
def test_create_gift_card_with_zero_balance_amount(
staff_api_client,
customer_user,
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py
new file mode 100644
index 0000000000..70bd1fa095
--- /dev/null
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py
@@ -0,0 +1,206 @@
+from unittest import mock
+
+import graphene
+
+from .....giftcard import GiftCardEvents
+from .....giftcard.error_codes import GiftCardErrorCode
+from .....giftcard.models import GiftCardEvent
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+GIFT_CARD_RESEND_MUTATION = """
+ mutation giftCardResend($input: GiftCardResendInput!) {
+ giftCardResend(input: $input) {
+ giftCard {
+ id
+ code
+ createdBy {
+ email
+ }
+ usedBy {
+ email
+ }
+ createdByEmail
+ usedByEmail
+ app {
+ name
+ }
+ events {
+ type
+ user {
+ email
+ }
+ app {
+ name
+ }
+ }
+ }
+ errors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_resend_gift_card(
+ notify_mock,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+):
+ # given
+ email = "[email protected]"
+ variables = {
+ "input": {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
+ "email": email,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_RESEND_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardResend"]["giftCard"]
+ errors = content["data"]["giftCardResend"]["errors"]
+
+ assert not errors
+ events = data["events"]
+ assert len(events) == 1
+ event = events[0]
+ assert event["type"] == GiftCardEvents.RESENT.upper()
+ assert event["user"]["email"] == staff_api_client.user.email
+
+ db_event = GiftCardEvent.objects.get()
+ assert db_event.parameters["email"] == email
+
+ assert notify_mock.call_count == 1
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_resend_gift_card_as_app(
+ notify_mock,
+ app_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+):
+ # given
+ variables = {
+ "input": {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ GIFT_CARD_RESEND_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardResend"]["giftCard"]
+ errors = content["data"]["giftCardResend"]["errors"]
+
+ assert not errors
+ events = data["events"]
+ assert len(events) == 1
+ event = events[0]
+ assert event["type"] == GiftCardEvents.RESENT.upper()
+ assert event["user"] is None
+ assert event["app"]["name"] == app_api_client.app.name
+
+ db_event = GiftCardEvent.objects.get()
+ assert db_event.parameters["email"] == gift_card.created_by_email
+
+ assert notify_mock.call_count == 1
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_update_gift_card_no_permission(
+ notify_mock,
+ staff_api_client,
+ gift_card,
+):
+ # given
+ variables = {
+ "input": {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_RESEND_MUTATION,
+ variables,
+ )
+
+ # then
+ assert not GiftCardEvent.objects.exists()
+ assert_no_permission(response)
+
+ notify_mock.assert_not_called()
+
+
[email protected]("saleor.plugins.manager.PluginsManager.notify")
+def test_resend_gift_card_malformed_email(
+ notify_mock,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+):
+ # given
+ variables = {
+ "input": {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
+ "email": "malformed",
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_RESEND_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardResend"]["giftCard"]
+ errors = content["data"]["giftCardResend"]["errors"]
+
+ assert not data
+ assert not GiftCardEvent.objects.exists()
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "email"
+ assert error["code"] == GiftCardErrorCode.INVALID.name
+
+ notify_mock.assert_not_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b98887831f..866a6bdda9 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2384,6 +2384,17 @@ input GiftCardFilterInput {
tag: String
}
+type GiftCardResend {
+ giftCard: GiftCard
+ giftCardErrors: [GiftCardError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
+ errors: [GiftCardError!]!
+}
+
+input GiftCardResendInput {
+ id: ID!
+ email: String
+}
+
type GiftCardSettings {
expiryType: GiftCardSettingsExpiryTypeEnum!
expiryPeriod: TimePeriod
@@ -3803,6 +3814,7 @@ type Mutation {
giftCardDelete(id: ID!): GiftCardDelete
giftCardDeactivate(id: ID!): GiftCardDeactivate
giftCardUpdate(id: ID!, input: GiftCardUpdateInput!): GiftCardUpdate
+ giftCardResend(input: GiftCardResendInput!): GiftCardResend
giftCardBulkDelete(ids: [ID]!): GiftCardBulkDelete
giftCardBulkActivate(ids: [ID]!): GiftCardBulkActivate
pluginUpdate(channelId: ID, id: ID!, input: PluginUpdateInput!): PluginUpdate