Skip to content

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

New events related to gift card changes (#9588)

SzymJ52adcd10d4e0
diff --git a/saleor/graphql/giftcard/bulk_mutations.py b/saleor/graphql/giftcard/bulk_mutations.py
index 131560b4cf..73d90af997 100644
--- a/saleor/graphql/giftcard/bulk_mutations.py
+++ b/saleor/graphql/giftcard/bulk_mutations.py
@@ -2,6 +2,7 @@ from typing import Iterable
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from ...core.permissions import GiftcardPermissions
from ...core.tracing import traced_atomic_transaction
@@ -69,6 +70,10 @@ class GiftCardBulkCreate(BaseMutation):
instances = cls.create_instances(input_data, info)
if tags:
cls.assign_gift_card_tags(instances, tags)
+
+ transaction.on_commit(
+ lambda: cls.call_gift_card_created_on_plugins(instances, info)
+ )
return cls(count=len(instances), gift_cards=instances)
@staticmethod
@@ -147,6 +152,11 @@ class GiftCardBulkCreate(BaseMutation):
for tag_instance in tags_instances.iterator():
tag_instance.gift_cards.set(instances)
+ @staticmethod
+ def call_gift_card_created_on_plugins(instances, info):
+ for instance in instances:
+ info.context.plugins.gift_card_created(instance)
+
class GiftCardBulkDelete(ModelBulkDeleteMutation):
class Arguments:
@@ -161,6 +171,13 @@ class GiftCardBulkDelete(ModelBulkDeleteMutation):
permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)
error_type_class = GiftCardError
+ @classmethod
+ def bulk_action(cls, info, queryset):
+ instances = [card for card in queryset]
+ queryset.delete()
+ for instance in instances:
+ info.context.plugins.gift_card_deleted(instance)
+
class GiftCardBulkActivate(BaseBulkMutation):
class Arguments:
@@ -192,6 +209,8 @@ class GiftCardBulkActivate(BaseBulkMutation):
events.gift_cards_activated_event(
gift_card_ids, user=info.context.user, app=info.context.app
)
+ for card in models.GiftCard.objects.filter(id__in=gift_card_ids):
+ info.context.plugins.gift_card_status_changed(card)
class GiftCardBulkDeactivate(BaseBulkMutation):
@@ -218,3 +237,5 @@ class GiftCardBulkDeactivate(BaseBulkMutation):
events.gift_cards_deactivated_event(
gift_card_ids, user=info.context.user, app=info.context.app
)
+ for card in models.GiftCard.objects.filter(id__in=gift_card_ids):
+ info.context.plugins.gift_card_status_changed(card)
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index 7fe39ffc36..26eedb0628 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -240,6 +240,7 @@ class GiftCardCreate(ModelMutation):
channel_slug=cleaned_input["channel"],
resending=False,
)
+ info.context.plugins.gift_card_created(instance)
@staticmethod
def assign_gift_card_tags(instance: models.GiftCard, tags_values: Iterable[str]):
@@ -338,6 +339,7 @@ class GiftCardUpdate(GiftCardCreate):
if tags_updated:
events.gift_card_tags_updated_event(instance, old_tags, user, app)
+ info.context.plugins.gift_card_updated(instance)
return cls.success_response(instance)
@classmethod
@@ -373,6 +375,10 @@ class GiftCardDelete(ModelDeleteMutation):
error_type_class = GiftCardError
error_type_field = "gift_card_errors"
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.gift_card_deleted(instance)
+
class GiftCardDeactivate(BaseMutation):
gift_card = graphene.Field(GiftCard, description="Deactivated gift card.")
@@ -399,6 +405,7 @@ class GiftCardDeactivate(BaseMutation):
events.gift_card_deactivated_event(
gift_card=gift_card, user=info.context.user, app=info.context.app
)
+ info.context.plugins.gift_card_status_changed(gift_card)
return GiftCardDeactivate(gift_card=gift_card)
@@ -428,6 +435,7 @@ class GiftCardActivate(BaseMutation):
events.gift_card_activated_event(
gift_card=gift_card, user=info.context.user, app=info.context.app
)
+ info.context.plugins.gift_card_status_changed(gift_card)
return GiftCardActivate(gift_card=gift_card)
@@ -556,4 +564,5 @@ class GiftCardAddNote(BaseMutation):
app=info.context.app,
message=cleaned_input["message"],
)
+ info.context.plugins.gift_card_updated(gift_card)
return GiftCardAddNote(gift_card=gift_card, event=event)
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
index 01859cce5e..bf8c7f3178 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
@@ -1,9 +1,12 @@
from datetime import date, timedelta
+from unittest import mock
import graphene
+from django.utils.functional import SimpleLazyObject
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
ACTIVATE_GIFT_CARD_MUTATION = """
@@ -179,3 +182,50 @@ def test_activate_expired_gift_card(
assert len(errors) == 1
assert errors[0]["field"] == "id"
assert errors[0]["code"] == GiftCardErrorCode.EXPIRED_GIFT_CARD.name
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_activate_gift_card_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ gift_card.is_active = False
+ gift_card.save(update_fields=["is_active"])
+ assert not gift_card.is_active
+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.id)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ ACTIVATE_GIFT_CARD_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardActivate"]["giftCard"]
+ assert data["isActive"]
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": variables["id"], "is_active": True},
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
index ea2ad69cbb..34bf6435aa 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py
@@ -1,10 +1,13 @@
from datetime import date, timedelta
+from unittest import mock
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import get_graphql_content
GIFT_CARD_ADD_NOTE_MUTATION = """
@@ -191,3 +194,53 @@ def test_gift_card_add_note_expired_card(
assert event.type == GiftCardEvents.NOTE_ADDED
assert event.user == staff_user
assert event.parameters == {"message": message}
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_gift_card_add_note_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ permission_manage_apps,
+ permission_manage_users,
+ permission_manage_gift_card,
+ gift_card,
+ staff_user,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)
+ message = "nuclear note"
+ variables = {"id": gift_card_id, "message": message}
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_ADD_NOTE_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_apps,
+ permission_manage_users,
+ permission_manage_gift_card,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardAddNote"]
+ assert data["giftCard"]
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),
+ "is_active": gift_card.is_active,
+ },
+ WebhookEventAsyncType.GIFT_CARD_UPDATED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
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 55cd13090e..edf2039637 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
@@ -1,4 +1,5 @@
from datetime import date, timedelta
+from unittest import mock
import graphene
@@ -180,3 +181,42 @@ def test_gift_card_bulk_activate_expired_cards(
]
for error in errors:
assert error in expected_errors
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_gift_card_bulk_activate_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ gift_card_expiry_date,
+ permission_manage_gift_card,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ gift_card.is_active = False
+ 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]
+ variables = {"ids": ids}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_GIFT_CARD_BULK_ACTIVATE,
+ variables,
+ permissions=(permission_manage_gift_card,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardBulkActivate"]
+
+ assert data["count"] == len(ids)
+ assert mocked_webhook_trigger.call_count == len(ids)
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py
index aa42b3e824..d17d303903 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py
@@ -1,4 +1,5 @@
from datetime import date, timedelta
+from unittest import mock
import pytest
@@ -161,6 +162,61 @@ def test_create_never_expiry_gift_cards(
assert not card_data["events"][0]["balance"]["oldCurrentBalance"]
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_create_gift_cards_trigger_webhooks(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ initial_balance = 100
+ currency = "USD"
+ tags = ["gift-card-tag", "gift-card-tag-2"]
+ count = 10
+ is_active = True
+ variables = {
+ "input": {
+ "count": count,
+ "balance": {
+ "amount": initial_balance,
+ "currency": currency,
+ },
+ "tags": tags,
+ "isActive": is_active,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_BULK_CREATE_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["giftCardBulkCreate"]["errors"]
+ data = content["data"]["giftCardBulkCreate"]
+
+ assert not errors
+ assert data["count"] == count
+ assert len(data["giftCards"]) == count
+ assert mocked_webhook_trigger.call_count == count
+
+
def test_create_gift_cards_with_expiry_date_by_app(
app_api_client,
permission_manage_gift_card,
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 4b18f404d5..9e4b0032f8 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
@@ -1,3 +1,5 @@
+from unittest import mock
+
import graphene
from .....giftcard import GiftCardEvents
@@ -142,3 +144,39 @@ def test_gift_card_bulk_deactivate_by_customer(
# then
assert_no_permission(response)
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_gift_card_bulk_deactivate_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ gift_card_expiry_date,
+ permission_manage_gift_card,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ 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}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_GIFT_CARD_BULK_DEACTIVATE,
+ variables,
+ permissions=(permission_manage_gift_card,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardBulkDeactivate"]
+
+ assert data["count"] == len(ids)
+ assert mocked_webhook_trigger.call_count == len(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 bce43df9bd..0b91df043e 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
@@ -1,3 +1,5 @@
+from unittest import mock
+
import graphene
from .....giftcard.models import GiftCard
@@ -84,3 +86,39 @@ def test_gift_card_bulk_delete_by_customer(
# then
assert_no_permission(response)
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_gift_card_bulk_delete_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ permission_manage_gift_card,
+ gift_card,
+ gift_card_expiry_date,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ 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}
+
+ # when
+ response = staff_api_client.post_graphql(
+ GIFT_CARD_BULK_DELETE_MUTATION,
+ variables,
+ permissions=(permission_manage_gift_card,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardBulkDelete"]
+
+ assert not data["errors"]
+ assert not GiftCard.objects.filter(id__in=gift_card_pks)
+ assert mocked_webhook_trigger.call_count == len(gift_card_pks)
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 c31a8b207d..6ab98132b2 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py
@@ -1,11 +1,14 @@
from datetime import date, timedelta
from unittest import mock
+import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
from .....giftcard.models import GiftCard
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
CREATE_GIFT_CARD_MUTATION = """
@@ -617,3 +620,63 @@ def test_create_gift_card_with_expiry_date_type_invalid(
assert len(errors) == 1
assert errors[0]["field"] == "expiryDate"
assert errors[0]["code"] == GiftCardErrorCode.INVALID.name
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_create_gift_card_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ app_api_client,
+ permission_manage_gift_card,
+ permission_manage_users,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ initial_balance = 100
+ currency = "USD"
+ tag = "gift-card-tag"
+ note = "This is gift card note that will be save in gift card event."
+ variables = {
+ "input": {
+ "balance": {
+ "amount": initial_balance,
+ "currency": currency,
+ },
+ "addTags": [tag],
+ "note": note,
+ "expiryDate": None,
+ "isActive": False,
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CREATE_GIFT_CARD_MUTATION,
+ variables,
+ permissions=[permission_manage_gift_card, permission_manage_users],
+ )
+ gift_card = GiftCard.objects.last()
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["giftCardCreate"]["errors"]
+ data = content["data"]["giftCardCreate"]["giftCard"]
+
+ assert not errors
+ assert data["code"]
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),
+ "is_active": gift_card.is_active,
+ },
+ WebhookEventAsyncType.GIFT_CARD_CREATED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: app_api_client.app),
+ )
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_deactivate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_deactivate.py
index f6ad2a8560..5fece730b4 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_deactivate.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_deactivate.py
@@ -1,6 +1,10 @@
+from unittest import mock
+
import graphene
+from django.utils.functional import SimpleLazyObject
from .....giftcard import GiftCardEvents
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
DEACTIVATE_GIFT_CARD_MUTATION = """
@@ -155,3 +159,48 @@ def test_deactivate_inactive_gift_card(
data = content["data"]["giftCardDeactivate"]["giftCard"]
assert data["isActive"] is False
assert not data["events"]
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_deactivate_gift_card_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ assert gift_card.is_active
+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.id)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ DEACTIVATE_GIFT_CARD_MUTATION,
+ variables,
+ permissions=[
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardDeactivate"]["giftCard"]
+ assert not data["isActive"]
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": variables["id"], "is_active": False},
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_delete.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_delete.py
index fd0c40a44b..99cf258faf 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_delete.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_delete.py
@@ -1,6 +1,10 @@
+from unittest import mock
+
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
DELETE_GIFT_CARD_MUTATION = """
@@ -78,3 +82,41 @@ def test_delete_gift_card_by_customer(app_api_client, gift_card):
# then
assert_no_permission(response)
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_delete_gift_card_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ DELETE_GIFT_CARD_MUTATION,
+ {"id": id},
+ permissions=(permission_manage_gift_card,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["giftCardDelete"]["giftCard"]
+
+ assert data["id"] == id
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": id, "is_active": gift_card.is_active},
+ WebhookEventAsyncType.GIFT_CARD_DELETED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
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 821c0909b9..1272fa52b1 100644
--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py
@@ -1,11 +1,14 @@
from datetime import date, timedelta
+from unittest import mock
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
from .....giftcard.models import GiftCardTag
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
UPDATE_GIFT_CARD_MUTATION = """
@@ -725,3 +728,63 @@ def test_update_gift_card_duplicated_tags_item(
assert len(errors) == 1
assert errors[0]["field"] == "tags"
assert errors[0]["code"] == GiftCardErrorCode.DUPLICATED_INPUT_ITEM.name
+
+
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_update_gift_card_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ gift_card,
+ permission_manage_gift_card,
+ permission_manage_users,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ initial_balance = 100.0
+ date_value = date.today() + timedelta(days=365)
+ new_tag = "new-gift-card-tag"
+ variables = {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),
+ "input": {
+ "balanceAmount": initial_balance,
+ "addTags": [new_tag],
+ "expiryDate": date_value,
+ },
+ }
+
+ # 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
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),
+ "is_active": gift_card.is_active,
+ },
+ WebhookEventAsyncType.GIFT_CARD_UPDATED,
+ [any_webhook],
+ gift_card,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5cd2905733..069c66a1a8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1117,6 +1117,18 @@ enum WebhookEventTypeEnum {
"""A channel status is changed."""
CHANNEL_STATUS_CHANGED
+ """A new gift card created."""
+ GIFT_CARD_CREATED
+
+ """A gift card is updated."""
+ GIFT_CARD_UPDATED
+
+ """A gift card is deleted."""
+ GIFT_CARD_DELETED
+
+ """A gift card status is changed."""
+ GIFT_CARD_STATUS_CHANGED
+
"""A new order is placed."""
ORDER_CREATED
@@ -1304,6 +1316,18 @@ enum WebhookEventTypeAsyncEnum {
"""A channel status is changed."""
CHANNEL_STATUS_CHANGED
+ """A new gift card created."""
+ GIFT_CARD_CREATED
+
+ """A gift card is updated."""
+ GIFT_CARD_UPDATED
+
+ """A gift card is deleted."""
+ GIFT_CARD_DELETED
+
+ """A gift card status is changed."""
+ GIFT_CARD_STATUS_CHANGED
+
"""A new order is placed."""
ORDER_CREATED
@@ -1788,6 +1812,10 @@ enum WebhookSampleEventTypeEnum {
CHANNEL_UPDATED
CHANNEL_DELETED
CHANNEL_STATUS_CHANGED
+ GIFT_CARD_CREATED
+ GIFT_CARD_UPDATED
+ GIFT_CARD_DELETED
+ GIFT_CARD_STATUS_CHANGED
ORDER_CREATED
ORDER_CONFIRMED
ORDER_FULLY_PAID
@@ -16617,7 +16645,7 @@ type Subscription {
event: Event
}
-union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TranslationCreated | TranslationUpdated
+union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | OrderCreated | OrderUpdated | OrderConfirmed | OrderFullyPaid | OrderCancelled | OrderFulfilled | DraftOrderCreated | DraftOrderUpdated | DraftOrderDeleted | ProductCreated | ProductUpdated | ProductDeleted | ProductVariantCreated | ProductVariantUpdated | ProductVariantOutOfStock | ProductVariantBackInStock | ProductVariantDeleted | SaleCreated | SaleUpdated | SaleDeleted | InvoiceRequested | InvoiceDeleted | InvoiceSent | FulfillmentCreated | FulfillmentCanceled | CustomerCreated | CustomerUpdated | CollectionCreated | CollectionUpdated | CollectionDeleted | CheckoutCreated | CheckoutUpdated | PageCreated | PageUpdated | PageDeleted | ShippingPriceCreated | ShippingPriceUpdated | ShippingPriceDeleted | ShippingZoneCreated | ShippingZoneUpdated | ShippingZoneDeleted | TranslationCreated | TranslationUpdated
type CategoryCreated {
"""
@@ -16668,6 +16696,34 @@ type ChannelStatusChanged {
channel: Channel
}
+type GiftCardCreated {
+ """
+ New in Saleor 3.2. Look up a gift card. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ giftCard: GiftCard
+}
+
+type GiftCardUpdated {
+ """
+ New in Saleor 3.2. Look up a gift card. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ giftCard: GiftCard
+}
+
+type GiftCardDeleted {
+ """
+ New in Saleor 3.2. Look up a gift card. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ giftCard: GiftCard
+}
+
+type GiftCardStatusChanged {
+ """
+ New in Saleor 3.2. Look up a gift card. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ giftCard: GiftCard
+}
+
type OrderCreated {
"""
New in Saleor 3.2. Look up an order. Note: this feature is in a preview state and can be subject to changes at later point.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index bbf9eb2a7c..4a25450e14 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -37,6 +37,10 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.COLLECTION_DELETED: "A collection is deleted.",
WebhookEventAsyncType.CUSTOMER_CREATED: "A new customer account is created.",
WebhookEventAsyncType.CUSTOMER_UPDATED: "A customer account is updated.",
+ WebhookEventAsyncType.GIFT_CARD_CREATED: "A new gift card created.",
+ WebhookEventAsyncType.GIFT_CARD_UPDATED: "A gift card is updated.",
+ WebhookEventAsyncType.GIFT_CARD_DELETED: "A gift card is deleted.",
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: "A gift card status is changed.",
WebhookEventAsyncType.NOTIFY_USER: "User notification triggered.",
WebhookEventAsyncType.ORDER_CREATED: "A new order is placed.",
WebhookEventAsyncType.ORDER_CONFIRMED: order_confirmed_event_enum_description,
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 1f28d33b18..5a06e74ce6 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -133,6 +133,34 @@ class DraftOrderDeleted(ObjectType, OrderBase):
...
+class GiftCardBase(AbstractType):
+ gift_card = graphene.Field(
+ "saleor.graphql.giftcard.types.GiftCard",
+ description=f"{ADDED_IN_32} Look up a gift card. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_gift_card(root, info):
+ _, gift_card = root
+ return gift_card
+
+
+class GiftCardCreated(ObjectType, GiftCardBase):
+ ...
+
+
+class GiftCardUpdated(ObjectType, GiftCardBase):
+ ...
+
+
+class GiftCardDeleted(ObjectType, GiftCardBase):
+ ...
+
+
+class GiftCardStatusChanged(ObjectType, GiftCardBase):
+ ...
+
+
class ProductBase(AbstractType):
product = graphene.Field(
"saleor.graphql.product.types.Product",
@@ -503,6 +531,10 @@ class Event(Union):
ChannelUpdated,
ChannelDeleted,
ChannelStatusChanged,
+ GiftCardCreated,
+ GiftCardUpdated,
+ GiftCardDeleted,
+ GiftCardStatusChanged,
OrderCreated,
OrderUpdated,
OrderConfirmed,
@@ -558,6 +590,10 @@ class Event(Union):
WebhookEventAsyncType.CHANNEL_UPDATED: ChannelUpdated,
WebhookEventAsyncType.CHANNEL_DELETED: ChannelDeleted,
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED: ChannelStatusChanged,
+ WebhookEventAsyncType.GIFT_CARD_CREATED: GiftCardCreated,
+ WebhookEventAsyncType.GIFT_CARD_UPDATED: GiftCardUpdated,
+ WebhookEventAsyncType.GIFT_CARD_DELETED: GiftCardDeleted,
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: GiftCardStatusChanged,
WebhookEventAsyncType.ORDER_CREATED: OrderCreated,
WebhookEventAsyncType.ORDER_UPDATED: OrderUpdated,
WebhookEventAsyncType.ORDER_CONFIRMED: OrderConfirmed,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index de41737761..eba87c1577 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -35,6 +35,7 @@ if TYPE_CHECKING:
from ..core.taxes import TaxType
from ..discount import DiscountInfo
from ..discount.models import Sale
+ from ..giftcard.models import GiftCard
from ..graphql.discount.mutations import NodeCatalogueInfo
from ..invoice.models import Invoice
from ..order.models import Fulfillment, Order, OrderLine
@@ -434,6 +435,30 @@ class BasePlugin:
# Overwrite this method in case your plugin provides a list of tax categories.
get_tax_rate_type_choices: Callable[[List["TaxType"]], List["TaxType"]]
+ # Trigger when gift card is created.
+ #
+ # Overwrite this method if you need to trigger specific logic after a gift card is
+ # created.
+ gift_card_created: Callable[["GiftCard", None], None]
+
+ # Trigger when gift card is deleted.
+ #
+ # Overwrite this method if you need to trigger specific logic after a gift card is
+ # deleted.
+ gift_card_deleted: Callable[["GiftCard", None], None]
+
+ # Trigger when gift card is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a gift card is
+ # updated.
+ gift_card_updated: Callable[["GiftCard", None], None]
+
+ # Trigger when gift card status is changed.
+ #
+ # Overwrite this method if you need to trigger specific logic after a gift card
+ # status is changed.
+ gift_card_status_changed: Callable[["GiftCard", None], None]
+
initialize_payment: Callable[[dict], InitializedPaymentResponse]
# Trigger before invoice is deleted.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 520834ad9e..831c741456 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -43,6 +43,7 @@ if TYPE_CHECKING:
from ..checkout.models import Checkout
from ..core.middleware import Requestor
from ..discount.models import Sale
+ from ..giftcard.models import GiftCard
from ..invoice.models import Invoice
from ..order.models import Fulfillment, Order, OrderLine
from ..page.models import Page
@@ -817,6 +818,30 @@ class PluginsManager(PaymentInterface):
"channel_status_changed", default_value, channel
)
+ def gift_card_created(self, gift_card: "GiftCard"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "gift_card_created", default_value, gift_card
+ )
+
+ def gift_card_updated(self, gift_card: "GiftCard"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "gift_card_updated", default_value, gift_card
+ )
+
+ def gift_card_deleted(self, gift_card: "GiftCard"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "gift_card_deleted", default_value, gift_card
+ )
+
+ def gift_card_status_changed(self, gift_card: "GiftCard"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "gift_card_status_changed", default_value, gift_card
+ )
+
def shipping_price_created(self, shipping_method: "ShippingMethod"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 4d3b5fc68c..0a4a996458 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -53,6 +53,7 @@ if TYPE_CHECKING:
from ...channel.models import Channel
from ...checkout.models import Checkout
from ...discount.models import Sale
+ from ...giftcard.models import GiftCard
from ...graphql.discount.mutations import NodeCatalogueInfo
from ...invoice.models import Invoice
from ...order.models import Fulfillment, Order
@@ -158,6 +159,46 @@ class WebhookPlugin(BasePlugin):
payload, event_type, webhooks, channel, self.requestor
)
+ def _trigger_gift_card_event(self, event_type, gift_card):
+ if webhooks := get_webhooks_for_event(event_type):
+ payload = {
+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),
+ "is_active": gift_card.is_active,
+ }
+ trigger_webhooks_async(
+ payload, event_type, webhooks, gift_card, self.requestor
+ )
+
+ def gift_card_created(self, gift_card: "GiftCard", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_gift_card_event(
+ WebhookEventAsyncType.GIFT_CARD_CREATED, gift_card
+ )
+
+ def gift_card_updated(self, gift_card: "GiftCard", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_gift_card_event(
+ WebhookEventAsyncType.GIFT_CARD_UPDATED, gift_card
+ )
+
+ def gift_card_deleted(self, gift_card: "GiftCard", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_gift_card_event(
+ WebhookEventAsyncType.GIFT_CARD_DELETED, gift_card
+ )
+
+ def gift_card_status_changed(
+ self, gift_card: "GiftCard", previous_value: None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_gift_card_event(
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED, gift_card
+ )
+
def order_created(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 6fe71ff2fd..79d51ed5e1 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -161,6 +161,110 @@ def subscription_channel_status_changed_webhook(subscription_webhook):
)
+GIFT_CARD_DETAILS_FRAGMENT = """
+ fragment GiftCardDetails on GiftCard{
+ id
+ isActive
+ code
+ createdBy {
+ email
+ }
+ }
+"""
+
+GIFT_CARD_CREATED_SUBSCRIPTION_QUERY = (
+ GIFT_CARD_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on GiftCardCreated{
+ giftCard{
+ ...GiftCardDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_gift_card_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ GIFT_CARD_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.GIFT_CARD_CREATED
+ )
+
+
+GIFT_CARD_UPDATED_SUBSCRIPTION_QUERY = (
+ GIFT_CARD_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on GiftCardUpdated{
+ giftCard{
+ ...GiftCardDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_gift_card_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ GIFT_CARD_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.GIFT_CARD_UPDATED
+ )
+
+
+GIFT_CARD_DELETED_SUBSCRIPTION_QUERY = (
+ GIFT_CARD_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on GiftCardDeleted{
+ giftCard{
+ ...GiftCardDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_gift_card_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ GIFT_CARD_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.GIFT_CARD_DELETED
+ )
+
+
+GIFT_CARD_STATUS_CHANGED_SUBSCRIPTION_QUERY = (
+ GIFT_CARD_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on GiftCardStatusChanged{
+ giftCard{
+ ...GiftCardDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_gift_card_status_changed_webhook(subscription_webhook):
+ return subscription_webhook(
+ GIFT_CARD_STATUS_CHANGED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED,
+ )
+
+
SHIPPING_PRICE_CREATED_SUBSCRIPTION_QUERY = """
subscription{
event{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index fbb0853744..c9732dac6c 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -5,6 +5,7 @@ import graphene
import pytest
from .....channel.models import Channel
+from .....giftcard.models import GiftCard
from .....graphql.webhook.subscription_payload import validate_subscription_query
from .....product.models import Category
from .....shipping.models import ShippingMethod, ShippingZone
@@ -149,6 +150,99 @@ def test_channel_status_changed(
assert deliveries[0].webhook == webhooks[0]
+def generate_expected_payload_for_gift_card(gift_card, card_global_id):
+ return json.dumps(
+ {
+ "giftCard": {
+ "id": card_global_id,
+ "isActive": gift_card.is_active,
+ "code": gift_card.code,
+ "createdBy": {"email": gift_card.created_by.email},
+ },
+ "meta": None,
+ }
+ )
+
+
+def test_gift_card_created(gift_card, subscription_gift_card_created_webhook):
+ # given
+ webhooks = [subscription_gift_card_created_webhook]
+ event_type = WebhookEventAsyncType.GIFT_CARD_CREATED
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, gift_card, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_gift_card(gift_card, gift_card_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_gift_card_updated(gift_card, subscription_gift_card_updated_webhook):
+ # given
+ webhooks = [subscription_gift_card_updated_webhook]
+ event_type = WebhookEventAsyncType.GIFT_CARD_UPDATED
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, gift_card, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_gift_card(gift_card, gift_card_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_gift_card_deleted(gift_card, subscription_gift_card_deleted_webhook):
+ # given
+ webhooks = [subscription_gift_card_deleted_webhook]
+
+ gift_card_query = GiftCard.objects.filter(pk=gift_card.id)
+ gift_card_instances = [card for card in gift_card_query]
+ gift_card_query.delete()
+
+ event_type = WebhookEventAsyncType.GIFT_CARD_DELETED
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_instances[0].id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(
+ event_type, gift_card_instances[0], webhooks
+ )
+
+ # then
+ expected_payload = generate_expected_payload_for_gift_card(gift_card, gift_card_id)
+ assert gift_card_instances[0].id is not None
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
[email protected]("status", [True, False])
+def test_gift_card_status_changed(
+ status, gift_card, subscription_gift_card_status_changed_webhook
+):
+ # given
+ webhooks = [subscription_gift_card_status_changed_webhook]
+
+ gift_card.is_active = status
+ gift_card.save(update_fields=["is_active"])
+
+ event_type = WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, gift_card, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_gift_card(gift_card, gift_card_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_shipping_price_created(
shipping_method, subscription_shipping_price_created_webhook
):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 7619e04cf5..bd12b65a9d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5119,9 +5119,10 @@ def app(db):
@pytest.fixture
-def webhook_app(db, permission_manage_shipping):
+def webhook_app(db, permission_manage_shipping, permission_manage_gift_card):
app = App.objects.create(name="Sample app objects", is_active=True)
app.permissions.add(permission_manage_shipping)
+ app.permissions.add(permission_manage_gift_card)
return app
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index eeaed38e32..0fa86614ea 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -3,6 +3,7 @@ from ..core.permissions import (
ChannelPermissions,
CheckoutPermissions,
DiscountPermissions,
+ GiftcardPermissions,
OrderPermissions,
PagePermissions,
PaymentPermissions,
@@ -24,6 +25,11 @@ class WebhookEventAsyncType:
CHANNEL_DELETED = "channel_deleted"
CHANNEL_STATUS_CHANGED = "channel_status_changed"
+ GIFT_CARD_CREATED = "gift_card_created"
+ GIFT_CARD_UPDATED = "gift_card_updated"
+ GIFT_CARD_DELETED = "gift_card_deleted"
+ GIFT_CARD_STATUS_CHANGED = "gift_card_status_changed"
+
ORDER_CREATED = "order_created"
ORDER_CONFIRMED = "order_confirmed"
ORDER_FULLY_PAID = "order_fully_paid"
@@ -93,6 +99,10 @@ class WebhookEventAsyncType:
CHANNEL_UPDATED: "Channel updated",
CHANNEL_DELETED: "Channel deleted",
CHANNEL_STATUS_CHANGED: "Channel status changed",
+ GIFT_CARD_CREATED: "Gift card created",
+ GIFT_CARD_UPDATED: "Gift card updated",
+ GIFT_CARD_DELETED: "Gift card deleted",
+ GIFT_CARD_STATUS_CHANGED: "Gift card status changed",
ORDER_CREATED: "Order created",
ORDER_CONFIRMED: "Order confirmed",
ORDER_FULLY_PAID: "Order paid",
@@ -148,6 +158,10 @@ class WebhookEventAsyncType:
(CHANNEL_UPDATED, DISPLAY_LABELS[CHANNEL_UPDATED]),
(CHANNEL_DELETED, DISPLAY_LABELS[CHANNEL_DELETED]),
(CHANNEL_STATUS_CHANGED, DISPLAY_LABELS[CHANNEL_STATUS_CHANGED]),
+ (GIFT_CARD_CREATED, DISPLAY_LABELS[GIFT_CARD_CREATED]),
+ (GIFT_CARD_UPDATED, DISPLAY_LABELS[GIFT_CARD_UPDATED]),
+ (GIFT_CARD_DELETED, DISPLAY_LABELS[GIFT_CARD_DELETED]),
+ (GIFT_CARD_STATUS_CHANGED, DISPLAY_LABELS[GIFT_CARD_STATUS_CHANGED]),
(ORDER_CREATED, DISPLAY_LABELS[ORDER_CREATED]),
(ORDER_CONFIRMED, DISPLAY_LABELS[ORDER_CONFIRMED]),
(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),
@@ -204,6 +218,10 @@ class WebhookEventAsyncType:
CHANNEL_UPDATED: ChannelPermissions.MANAGE_CHANNELS,
CHANNEL_DELETED: ChannelPermissions.MANAGE_CHANNELS,
CHANNEL_STATUS_CHANGED: ChannelPermissions.MANAGE_CHANNELS,
+ GIFT_CARD_CREATED: GiftcardPermissions.MANAGE_GIFT_CARD,
+ GIFT_CARD_UPDATED: GiftcardPermissions.MANAGE_GIFT_CARD,
+ GIFT_CARD_DELETED: GiftcardPermissions.MANAGE_GIFT_CARD,
+ GIFT_CARD_STATUS_CHANGED: GiftcardPermissions.MANAGE_GIFT_CARD,
ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,
ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,
@@ -330,6 +348,10 @@ SUBSCRIBABLE_EVENTS = [
WebhookEventAsyncType.CHANNEL_UPDATED,
WebhookEventAsyncType.CHANNEL_DELETED,
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED,
+ WebhookEventAsyncType.GIFT_CARD_CREATED,
+ WebhookEventAsyncType.GIFT_CARD_UPDATED,
+ WebhookEventAsyncType.GIFT_CARD_DELETED,
+ WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED,
WebhookEventAsyncType.ORDER_CREATED,
WebhookEventAsyncType.ORDER_UPDATED,
WebhookEventAsyncType.ORDER_CONFIRMED,