Skip to content

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

Add `Channel` metadata updated webhook. (#13467)

Artur41345e402927
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8b7cf697d..1d81ccc5f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -90,6 +90,9 @@ Shipping methods can be removed by the user after it has been assigned to a chec
- Introduce `Saleor-Schema-Version` HTTP header in app manifest fetching and app installation handshake requests. - #13075 by @przlada
- Add `SHOP_METADATA_UPDATED` webhook - #13364, #13388 by @maarcingebala
- Called when metadata is changed for the Shop object via the generic metadata API or the `shopSettingsUpdate` mutation.
+- Add `CHANNEL_METADATA_UPDATED` webhook - #13448, by @Air-t
+ - Called when metadata is changed for the Channel object via the generic metadata API or the `channelUpdate` mutation.
+
### Other changes
- Add possibility to log without confirming email - #13059 by @kadewu
diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.py
index 7e657a1b32..76600be8b6 100644
--- a/saleor/graphql/channel/mutations/channel_update.py
+++ b/saleor/graphql/channel/mutations/channel_update.py
@@ -75,6 +75,12 @@ class ChannelUpdate(ModelMutation):
type=WebhookEventAsyncType.CHANNEL_UPDATED,
description="A channel was updated.",
),
+ WebhookEventInfo(
+ type=WebhookEventAsyncType.CHANNEL_METADATA_UPDATED,
+ description=(
+ "Optionally triggered when public or private metadata is updated."
+ ),
+ ),
]
support_meta_field = True
support_private_meta_field = True
@@ -217,3 +223,5 @@ class ChannelUpdate(ModelMutation):
def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
manager = get_plugin_manager_promise(info.context).get()
cls.call_event(manager.channel_updated, instance)
+ if cleaned_input.get("metadata"):
+ cls.call_event(manager.channel_metadata_updated, instance)
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index b853711dc2..52e139f75b 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -1,6 +1,6 @@
import json
from datetime import timedelta
-from unittest.mock import patch
+from unittest.mock import call, patch
import graphene
import pytest
@@ -495,7 +495,12 @@ def test_channel_update_mutation_trigger_webhook(
default_country = "FR"
variables = {
"id": channel_id,
- "input": {"name": name, "slug": slug, "defaultCountry": default_country},
+ "input": {
+ "name": name,
+ "slug": slug,
+ "defaultCountry": default_country,
+ "metadata": [{"key": "key", "value": "value"}],
+ },
}
# when
@@ -510,8 +515,7 @@ def test_channel_update_mutation_trigger_webhook(
data = content["data"]["channelUpdate"]
assert not data["errors"]
assert data["channel"]
-
- mocked_webhook_trigger.assert_called_once_with(
+ update_webhook_args = [
json.dumps(
{
"id": channel_id,
@@ -528,6 +532,11 @@ def test_channel_update_mutation_trigger_webhook(
[any_webhook],
channel_USD,
SimpleLazyObject(lambda: staff_api_client.user),
+ ]
+ metadata_webhook_args = update_webhook_args.copy()
+ metadata_webhook_args[1] = WebhookEventAsyncType.CHANNEL_METADATA_UPDATED
+ mocked_webhook_trigger.assert_has_calls(
+ [call(*update_webhook_args), call(*metadata_webhook_args)]
)
diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.py
index aed1306612..2e31109ba9 100644
--- a/saleor/graphql/meta/extra_methods.py
+++ b/saleor/graphql/meta/extra_methods.py
@@ -9,6 +9,11 @@ def extra_checkout_actions(instance, info: ResolveInfo, **data):
manager.checkout_metadata_updated(instance)
+def extra_channel_actions(instance, info: ResolveInfo, **data):
+ manager = get_plugin_manager_promise(info.context).get()
+ manager.channel_metadata_updated(instance)
+
+
def extra_collection_actions(instance, info: ResolveInfo, **data):
manager = get_plugin_manager_promise(info.context).get()
manager.collection_metadata_updated(instance)
@@ -77,6 +82,7 @@ TYPE_EXTRA_METHODS = {
"Collection": extra_collection_actions,
"Fulfillment": extra_fulfillment_actions,
"GiftCard": extra_gift_card_actions,
+ "Channel": extra_channel_actions,
"Order": extra_order_actions,
"Product": extra_product_actions,
"ProductVariant": extra_variant_actions,
diff --git a/saleor/graphql/meta/tests/mutations/test_channel.py b/saleor/graphql/meta/tests/mutations/test_channel.py
index ab6213ac9e..9a39fe5858 100644
--- a/saleor/graphql/meta/tests/mutations/test_channel.py
+++ b/saleor/graphql/meta/tests/mutations/test_channel.py
@@ -1,3 +1,5 @@
+from unittest import mock
+
import graphene
from . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
@@ -89,3 +91,67 @@ def test_add_private_metadata_for_channel_USD(
assert item_contains_proper_private_metadata(
response["data"]["updatePrivateMetadata"]["item"], channel_USD, channel_id
)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.channel_metadata_updated")
+def test_channel_update_metadata_trigger_webhook_when_metadata_changed(
+ mock_channel_metadata_updated,
+ staff_api_client,
+ permission_manage_channels,
+ channel_USD,
+):
+ # given
+ key, value = "public", "public_value"
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ assert channel_USD.metadata == {}
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_channels,
+ channel_id,
+ "Channel",
+ key=key,
+ value=value,
+ )
+
+ # then
+ channel_data = response["data"]["updateMetadata"]["item"]
+ assert item_contains_proper_public_metadata(
+ channel_data, channel_USD, channel_id, key=key, value=value
+ )
+ assert channel_data["metadata"] == [{"key": key, "value": value}]
+ mock_channel_metadata_updated.assert_called_once_with(channel_USD)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.channel_metadata_updated")
+def test_channel_update_metadata_does_not_trigger_webhook_when_metadata_unchanged(
+ mock_channel_metadata_updated,
+ staff_api_client,
+ permission_manage_channels,
+ channel_USD,
+):
+ # given
+ key = "public"
+ value = "public_value"
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ channel_USD.metadata = {key: value}
+ channel_USD.save()
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_channels,
+ channel_id,
+ "Channel",
+ key=key,
+ value=value,
+ )
+
+ # then
+ channel_data = response["data"]["updateMetadata"]["item"]
+ assert item_contains_proper_public_metadata(
+ channel_data, channel_USD, channel_id, key=key, value=value
+ )
+ assert channel_data["metadata"] == [{"key": key, "value": value}]
+ mock_channel_metadata_updated.assert_not_called()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index d246b4bb4b..4e50d216de 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1788,6 +1788,13 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""A channel status is changed."""
CHANNEL_STATUS_CHANGED
+ """
+ A channel metadata is updated.
+
+ Added in Saleor 3.15.
+ """
+ CHANNEL_METADATA_UPDATED
+
"""A new gift card created."""
GIFT_CARD_CREATED
@@ -2432,6 +2439,13 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""A channel status is changed."""
CHANNEL_STATUS_CHANGED
+ """
+ A channel metadata is updated.
+
+ Added in Saleor 3.15.
+ """
+ CHANNEL_METADATA_UPDATED
+
"""A new gift card created."""
GIFT_CARD_CREATED
@@ -3389,6 +3403,7 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
CHANNEL_UPDATED
CHANNEL_DELETED
CHANNEL_STATUS_CHANGED
+ CHANNEL_METADATA_UPDATED
GIFT_CARD_CREATED
GIFT_CARD_UPDATED
GIFT_CARD_DELETED
@@ -17317,6 +17332,7 @@ type Mutation {
Triggers the following webhook events:
- CHANNEL_UPDATED (async): A channel was updated.
+ - CHANNEL_METADATA_UPDATED (async): Optionally triggered when public or private metadata is updated.
"""
channelUpdate(
"""ID of a channel to update."""
@@ -17324,7 +17340,7 @@ type Mutation {
"""Fields required to update a channel."""
input: ChannelUpdateInput!
- ): ChannelUpdate @doc(category: "Channels") @webhookEventsInfo(asyncEvents: [CHANNEL_UPDATED], syncEvents: [])
+ ): ChannelUpdate @doc(category: "Channels") @webhookEventsInfo(asyncEvents: [CHANNEL_UPDATED, CHANNEL_METADATA_UPDATED], syncEvents: [])
"""
Delete a channel. Orders associated with the deleted channel will be moved to the target channel. Checkouts, product availability, and pricing will be removed.
@@ -26697,8 +26713,9 @@ Requires one of the following permissions when updating only orderSettings field
Triggers the following webhook events:
- CHANNEL_UPDATED (async): A channel was updated.
+- CHANNEL_METADATA_UPDATED (async): Optionally triggered when public or private metadata is updated.
"""
-type ChannelUpdate @doc(category: "Channels") @webhookEventsInfo(asyncEvents: [CHANNEL_UPDATED], syncEvents: []) {
+type ChannelUpdate @doc(category: "Channels") @webhookEventsInfo(asyncEvents: [CHANNEL_UPDATED, CHANNEL_METADATA_UPDATED], syncEvents: []) {
channelErrors: [ChannelError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")
errors: [ChannelError!]!
channel: Channel
@@ -29596,6 +29613,28 @@ type ChannelStatusChanged implements Event @doc(category: "Channels") {
channel: Channel
}
+"""
+Event sent when channel metadata is updated.
+
+Added in Saleor 3.15.
+"""
+type ChannelMetadataUpdated implements Event @doc(category: "Channels") {
+ """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 channel the event relates to."""
+ channel: Channel
+}
+
"""
Event sent when new gift card is created.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 4498e1d9c0..a76d47996f 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -62,6 +62,8 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.CHANNEL_UPDATED: "A channel is updated.",
WebhookEventAsyncType.CHANNEL_DELETED: "A channel is deleted.",
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED: "A channel status is changed.",
+ WebhookEventAsyncType.CHANNEL_METADATA_UPDATED: "A channel metadata is updated."
+ + ADDED_IN_315,
WebhookEventAsyncType.CHECKOUT_CREATED: "A new checkout is created.",
WebhookEventAsyncType.CHECKOUT_UPDATED: checkout_updated_event_enum_description,
WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED: (
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index f4c5ae46fe..b070f730cb 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -446,6 +446,14 @@ class ChannelStatusChanged(SubscriptionObjectType, ChannelBase):
description = "Event sent when channel status has changed." + ADDED_IN_32
+class ChannelMetadataUpdated(SubscriptionObjectType, ChannelBase):
+ class Meta:
+ root_type = "Channel"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "Event sent when channel metadata is updated." + ADDED_IN_315
+
+
class OrderBase(AbstractType):
order = graphene.Field(
"saleor.graphql.order.types.Order",
@@ -2146,6 +2154,7 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.CHANNEL_UPDATED: ChannelUpdated,
WebhookEventAsyncType.CHANNEL_DELETED: ChannelDeleted,
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED: ChannelStatusChanged,
+ WebhookEventAsyncType.CHANNEL_METADATA_UPDATED: ChannelMetadataUpdated,
WebhookEventAsyncType.GIFT_CARD_CREATED: GiftCardCreated,
WebhookEventAsyncType.GIFT_CARD_UPDATED: GiftCardUpdated,
WebhookEventAsyncType.GIFT_CARD_DELETED: GiftCardDeleted,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index a9db158cc3..2934c773a8 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -404,6 +404,12 @@ class BasePlugin:
# status is changed.
channel_status_changed: Callable[["Channel", None], None]
+ # Trigger when channel metadata is changed.
+ #
+ # Overwrite this method if you need to trigger specific logic after a channel
+ # metadata is changed.
+ channel_metadata_updated: Callable[["Channel", None], None]
+
change_user_address: Callable[
["Address", Union[str, None], Union["User", None], bool, "Address"], "Address"
]
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 791de4f5c7..4e1909118f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1191,6 +1191,12 @@ class PluginsManager(PaymentInterface):
"channel_status_changed", default_value, channel
)
+ def channel_metadata_updated(self, channel: "Channel"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "channel_metadata_updated", default_value, channel
+ )
+
def gift_card_created(self, gift_card: "GiftCard"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 878544aa86..937f66fee0 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -441,6 +441,15 @@ class WebhookPlugin(BasePlugin):
WebhookEventAsyncType.CHANNEL_STATUS_CHANGED, channel
)
+ def channel_metadata_updated(
+ self, channel: "Channel", previous_value: None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self.__trigger_channel_event(
+ WebhookEventAsyncType.CHANNEL_METADATA_UPDATED, channel
+ )
+
def _trigger_gift_card_event(self, event_type, gift_card: "GiftCard"):
if webhooks := get_webhooks_for_event(event_type):
payload = self._serialize_payload(
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 36c4c54401..46df36bc72 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -51,6 +51,7 @@ class WebhookEventAsyncType:
CHANNEL_UPDATED = "channel_updated"
CHANNEL_DELETED = "channel_deleted"
CHANNEL_STATUS_CHANGED = "channel_status_changed"
+ CHANNEL_METADATA_UPDATED = "channel_metadata_updated"
GIFT_CARD_CREATED = "gift_card_created"
GIFT_CARD_UPDATED = "gift_card_updated"
@@ -271,6 +272,10 @@ class WebhookEventAsyncType:
"name": "Channel status changed",
"permission": ChannelPermissions.MANAGE_CHANNELS,
},
+ CHANNEL_METADATA_UPDATED: {
+ "name": "Channel metadata updated",
+ "permission": ChannelPermissions.MANAGE_CHANNELS,
+ },
GIFT_CARD_CREATED: {
"name": "Gift card created",
"permission": GiftcardPermissions.MANAGE_GIFT_CARD,