Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `GIFT_CARD_SENT` async event (#12472)
Rafał Pitoń4f70686fa303
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 480ea24dcd..f2c049257f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -139,6 +139,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `requiredSaleorVersion` field to the App manifest determining the required Saleor version as semver range - #12164 by @przlada- Add new field `author` to the App manifest - #12166 by @przlada+- Add `GIFT_CARD_SENT` asynchronous event to webhooks - #12472 by @rafalp# 3.12.0diff --git a/saleor/giftcard/notifications.py b/saleor/giftcard/notifications.pyindex a2eb734ed0..305f950eb9 100644--- a/saleor/giftcard/notifications.py+++ b/saleor/giftcard/notifications.py@@ -36,6 +36,7 @@ def send_gift_card_notification(manager.notify(NotifyEventType.SEND_GIFT_CARD, payload=payload, channel_slug=channel_slug)+ manager.gift_card_sent(gift_card, channel_slug, email)def get_default_gift_card_payload(gift_card: "GiftCard"):diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.pyindex ac1af32c47..d1659118d4 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py@@ -695,6 +695,85 @@ def test_create_gift_card_trigger_webhook()+@freeze_time("2022-05-12 12:00:00")[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_create_gift_card_with_email_triggers_gift_card_sent_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ app_api_client,+ channel_USD,+ customer_user,+ 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,+ "channel": channel_USD.slug,+ "userEmail": customer_user.email,+ }+ }++ # 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_any_call(+ json.dumps(+ {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),+ "is_active": gift_card.is_active,+ "channel_slug": channel_USD.slug,+ "sent_to_email": customer_user.email,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: app_api_client.app)+ )+ ),+ },+ cls=CustomJsonEncoder,+ ),+ WebhookEventAsyncType.GIFT_CARD_SENT,+ [any_webhook],+ {+ "gift_card": gift_card,+ "channel_slug": channel_USD.slug,+ "sent_to_email": customer_user.email,+ },+ SimpleLazyObject(lambda: app_api_client.app),+ )++def test_create_gift_card_with_code(staff_api_client,permission_manage_gift_card,diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.pyindex 1c99dab406..a0ec3225c8 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py@@ -1,10 +1,16 @@+import jsonfrom datetime import date, timedeltafrom unittest import mockimport graphene+from django.utils.functional import SimpleLazyObject+from freezegun import freeze_time+from .....core.utils.json_serializer import CustomJsonEncoderfrom .....giftcard.error_codes import GiftCardErrorCodefrom .....giftcard.models import GiftCardEvent+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import assert_no_permission, get_graphql_contentGIFT_CARD_RESEND_MUTATION = """@@ -216,6 +222,79 @@ def test_resend_gift_card_malformed_email(send_notification_mock.assert_not_called()+@freeze_time("2022-05-12 12:00:00")[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_resend_gift_card_triggers_gift_card_sent_event(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ gift_card,+ channel_USD,+ 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"]++ email = "[email protected]"+ variables = {+ "input": {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "email": email,+ "channel": channel_USD.slug,+ }+ }++ # 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+ assert data++ mocked_webhook_trigger.assert_any_call(+ json.dumps(+ {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),+ "is_active": gift_card.is_active,+ "channel_slug": channel_USD.slug,+ "sent_to_email": email,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ cls=CustomJsonEncoder,+ ),+ WebhookEventAsyncType.GIFT_CARD_SENT,+ [any_webhook],+ {+ "gift_card": gift_card,+ "channel_slug": channel_USD.slug,+ "sent_to_email": email,+ },+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_resend_gift_card_expired_card(staff_api_client,gift_card,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 8302b4881c..13fe921363 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1734,6 +1734,15 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {"""A gift card is deleted."""GIFT_CARD_DELETED+ """+ A gift card has been sent.++ Added in Saleor 3.13.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ GIFT_CARD_SENT+"""A gift card status is changed."""GIFT_CARD_STATUS_CHANGED@@ -2352,6 +2361,15 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {"""A gift card is deleted."""GIFT_CARD_DELETED+ """+ A gift card has been sent.++ Added in Saleor 3.13.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ GIFT_CARD_SENT+"""A gift card status is changed."""GIFT_CARD_STATUS_CHANGED@@ -3214,6 +3232,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {GIFT_CARD_CREATEDGIFT_CARD_UPDATEDGIFT_CARD_DELETED+ GIFT_CARD_SENTGIFT_CARD_STATUS_CHANGEDGIFT_CARD_METADATA_UPDATEDMENU_CREATED@@ -26681,6 +26700,36 @@ type GiftCardDeleted implements Event @doc(category: "Gift cards") {giftCard: GiftCard}+"""+Event sent when gift card is e-mailed.++Added in Saleor 3.13.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type GiftCardSent implements Event @doc(category: "Gift cards") {+ """Time of the event."""+ issuedAt: DateTime++ """Saleor version that triggered the event."""+ version: String++ """The user or application that triggered the event."""+ issuingPrincipal: IssuingPrincipal++ """The application receiving the webhook."""+ recipient: App++ """The gift card the event relates to."""+ giftCard: GiftCard++ """Slug of a channel for which this gift card email was sent."""+ channel: String++ """E-mail address to which gift card was sent."""+ sentToEmail: String+}+"""Event sent when gift card status has changed.diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex f27a5a94ab..595ed5c7c1 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -72,6 +72,9 @@ WEBHOOK_EVENT_DESCRIPTION = {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_SENT: (+ "A gift card has been sent." + ADDED_IN_313 + PREVIEW_FEATURE+ ),WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: "A gift card status is changed.",WebhookEventAsyncType.GIFT_CARD_METADATA_UPDATED: ("A gift card metadata is updated." + ADDED_IN_38 + PREVIEW_FEATUREdiff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex 5982eb1271..2542f28db9 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -562,6 +562,38 @@ class GiftCardDeleted(SubscriptionObjectType, GiftCardBase):)+class GiftCardSent(SubscriptionObjectType, GiftCardBase):+ channel = graphene.String(+ description="Slug of a channel for which this gift card email was sent."+ )+ sent_to_email = graphene.String(+ description="E-mail address to which gift card was sent.",+ )++ class Meta:+ root_type = "GiftCard"+ enable_dry_run = True+ interfaces = (Event,)+ description = (+ "Event sent when gift card is e-mailed." + ADDED_IN_313 + PREVIEW_FEATURE+ )++ @staticmethod+ def resolve_gift_card(root, info: ResolveInfo):+ _, data = root+ return data["gift_card"]++ @staticmethod+ def resolve_channel(root, info: ResolveInfo):+ _, data = root+ return data["channel_slug"]++ @staticmethod+ def resolve_sent_to_email(root, info: ResolveInfo):+ _, data = root+ return data["sent_to_email"]++class GiftCardStatusChanged(SubscriptionObjectType, GiftCardBase):class Meta:root_type = "GiftCard"@@ -2179,6 +2211,7 @@ WEBHOOK_TYPES_MAP = {WebhookEventAsyncType.GIFT_CARD_CREATED: GiftCardCreated,WebhookEventAsyncType.GIFT_CARD_UPDATED: GiftCardUpdated,WebhookEventAsyncType.GIFT_CARD_DELETED: GiftCardDeleted,+ WebhookEventAsyncType.GIFT_CARD_SENT: GiftCardSent,WebhookEventAsyncType.GIFT_CARD_STATUS_CHANGED: GiftCardStatusChanged,WebhookEventAsyncType.GIFT_CARD_METADATA_UPDATED: GiftCardMetadataUpdated,WebhookEventAsyncType.MENU_CREATED: MenuCreated,diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.pyindex d5f7537fc4..38e2bab091 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py@@ -220,6 +220,7 @@ def async_subscription_webhooks_with_root_objects(subscription_gift_card_created_webhook,subscription_gift_card_updated_webhook,subscription_gift_card_deleted_webhook,+ subscription_gift_card_sent_webhook,subscription_gift_card_status_changed_webhook,subscription_gift_card_metadata_updated_webhook,subscription_menu_created_webhook,@@ -379,6 +380,7 @@ def async_subscription_webhooks_with_root_objects(events.GIFT_CARD_CREATED: [subscription_gift_card_created_webhook, gift_card],events.GIFT_CARD_UPDATED: [subscription_gift_card_updated_webhook, gift_card],events.GIFT_CARD_DELETED: [subscription_gift_card_deleted_webhook, gift_card],+ events.GIFT_CARD_SENT: [subscription_gift_card_sent_webhook, gift_card],events.GIFT_CARD_STATUS_CHANGED: [subscription_gift_card_status_changed_webhook,gift_card,diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex d23c26f17a..388d6717b8 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1169,6 +1169,16 @@ class PluginsManager(PaymentInterface):"gift_card_deleted", default_value, gift_card)+ def gift_card_sent(self, gift_card: "GiftCard", channel_slug: str, email: str):+ default_value = None+ return self.__run_method_on_plugins(+ "gift_card_sent",+ default_value,+ gift_card,+ channel_slug,+ email,+ )+def gift_card_status_changed(self, gift_card: "GiftCard"):default_value = Nonereturn self.__run_method_on_plugins(diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 502ee77121..51761cf1da 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -347,7 +347,7 @@ class WebhookPlugin(BasePlugin):WebhookEventAsyncType.CHANNEL_STATUS_CHANGED, channel)- def _trigger_gift_card_event(self, event_type, gift_card):+ def _trigger_gift_card_event(self, event_type, gift_card: "GiftCard"):if webhooks := get_webhooks_for_event(event_type):payload = self._serialize_payload({@@ -381,6 +381,39 @@ class WebhookPlugin(BasePlugin):WebhookEventAsyncType.GIFT_CARD_DELETED, gift_card)+ def gift_card_sent(+ self,+ gift_card: "GiftCard",+ channel_slug: str,+ sent_to_email: str,+ previous_value: None,+ ) -> None:+ if not self.active:+ return previous_value++ event_type = WebhookEventAsyncType.GIFT_CARD_SENT+ if webhooks := get_webhooks_for_event(event_type):+ payload = self._serialize_payload(+ {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.id),+ "is_active": gift_card.is_active,+ "channel_slug": channel_slug,+ "sent_to_email": sent_to_email,+ "meta": self._generate_meta(),+ }+ )+ trigger_webhooks_async(+ payload,+ event_type,+ webhooks,+ {+ "gift_card": gift_card,+ "channel_slug": channel_slug,+ "sent_to_email": sent_to_email,+ },+ self.requestor,+ )+def gift_card_metadata_updated(self, gift_card: "GiftCard", previous_value: None) -> None:diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex 30a2985154..9b924dbf6d 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -182,6 +182,13 @@ def subscription_gift_card_deleted_webhook(subscription_webhook):)+def subscription_gift_card_sent_webhook(subscription_webhook):+ return subscription_webhook(+ queries.GIFT_CARD_SENT, WebhookEventAsyncType.GIFT_CARD_SENT+ )++@pytest.fixturedef subscription_gift_card_status_changed_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 0070c15fb7..f6febe156a 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -253,6 +253,24 @@ GIFT_CARD_DELETED = ()+GIFT_CARD_SENT = (+ fragments.GIFT_CARD_DETAILS+ + """+ subscription{+ event{+ ...on GiftCardSent {+ giftCard{+ ...GiftCardDetails+ }+ channel+ sentToEmail+ }+ }+ }+"""+)++GIFT_CARD_STATUS_CHANGED = (fragments.GIFT_CARD_DETAILS+ """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.pyindex 5242c315ea..77c5c3d896 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@@ -523,6 +523,39 @@ def test_gift_card_deleted(gift_card, subscription_gift_card_deleted_webhook):assert deliveries[0].webhook == webhooks[0]+def test_gift_card_sent(gift_card, channel_USD, subscription_gift_card_sent_webhook):+ # given+ webhooks = [subscription_gift_card_sent_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_SENT+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_instances[0].id)++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type,+ {+ "gift_card": gift_card_instances[0],+ "channel_slug": channel_USD.slug,+ "sent_to_email": "[email protected]",+ },+ webhooks,+ )++ # then+ expected_payload = json.loads(generate_gift_card_payload(gift_card, gift_card_id))+ expected_payload["channel"] = channel_USD.slug+ expected_payload["sentToEmail"] = "[email protected]"++ assert gift_card_instances[0].id is not None+ assert deliveries[0].payload.payload == json.dumps(expected_payload)+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++@pytest.mark.parametrize("status", [True, False])def test_gift_card_status_changed(status, gift_card, subscription_gift_card_status_changed_webhookdiff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex bd0c6b0f19..ad0a8cf9fa 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -48,6 +48,7 @@ class WebhookEventAsyncType:GIFT_CARD_CREATED = "gift_card_created"GIFT_CARD_UPDATED = "gift_card_updated"GIFT_CARD_DELETED = "gift_card_deleted"+ GIFT_CARD_SENT = "gift_card_sent"GIFT_CARD_STATUS_CHANGED = "gift_card_status_changed"GIFT_CARD_METADATA_UPDATED = "gift_card_metadata_updated"@@ -190,6 +191,7 @@ class WebhookEventAsyncType:GIFT_CARD_CREATED: "Gift card created",GIFT_CARD_UPDATED: "Gift card updated",GIFT_CARD_DELETED: "Gift card deleted",+ GIFT_CARD_SENT: "Gift card sent",GIFT_CARD_STATUS_CHANGED: "Gift card status changed",GIFT_CARD_METADATA_UPDATED: "Gift card metadata updated",MENU_CREATED: "Menu created",@@ -307,6 +309,7 @@ class WebhookEventAsyncType:(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_SENT, DISPLAY_LABELS[GIFT_CARD_SENT]),(GIFT_CARD_STATUS_CHANGED, DISPLAY_LABELS[GIFT_CARD_STATUS_CHANGED]),(GIFT_CARD_METADATA_UPDATED, DISPLAY_LABELS[GIFT_CARD_METADATA_UPDATED]),(MENU_CREATED, DISPLAY_LABELS[MENU_CREATED]),@@ -434,6 +437,7 @@ class WebhookEventAsyncType:GIFT_CARD_CREATED: GiftcardPermissions.MANAGE_GIFT_CARD,GIFT_CARD_UPDATED: GiftcardPermissions.MANAGE_GIFT_CARD,GIFT_CARD_DELETED: GiftcardPermissions.MANAGE_GIFT_CARD,+ GIFT_CARD_SENT: GiftcardPermissions.MANAGE_GIFT_CARD,GIFT_CARD_STATUS_CHANGED: GiftcardPermissions.MANAGE_GIFT_CARD,GIFT_CARD_METADATA_UPDATED: GiftcardPermissions.MANAGE_GIFT_CARD,MENU_CREATED: MenuPermissions.MANAGE_MENUS,