Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
New events for changes related to channels (#9570)
SzymJe5d78c63edd2
diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.pyindex 304cc5c48f..49fdc5fdb3 100644--- a/saleor/graphql/channel/mutations.py+++ b/saleor/graphql/channel/mutations.py@@ -80,6 +80,10 @@ class ChannelCreate(ModelMutation):if shipping_zones:instance.shipping_zones.add(*shipping_zones)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.channel_created(instance)+class ChannelUpdateInput(ChannelInput):name = graphene.String(description="Name of the channel.")@@ -155,6 +159,10 @@ class ChannelUpdate(ModelMutation):shipping_method_ids, [instance.id])+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.channel_updated(instance)+class ChannelDeleteInput(graphene.InputObjectType):channel_id = graphene.ID(@@ -240,6 +248,10 @@ class ChannelDelete(ModelDeleteMutation):)cls.delete_checkouts(origin_channel.id)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.channel_deleted(instance)+@classmethoddef perform_mutation(cls, _root, info, **data):origin_channel = cls.get_node_or_error(info, data["id"], only_type=Channel)@@ -375,7 +387,7 @@ class ChannelActivate(BaseMutation):cls.clean_channel_availability(channel)channel.is_active = Truechannel.save(update_fields=["is_active"])-+ info.context.plugins.channel_status_changed(channel)return ChannelActivate(channel=channel)@@ -409,5 +421,5 @@ class ChannelDeactivate(BaseMutation):cls.clean_channel_availability(channel)channel.is_active = Falsechannel.save(update_fields=["is_active"])-+ info.context.plugins.channel_status_changed(channel)return ChannelDeactivate(channel=channel)diff --git a/saleor/graphql/channel/tests/test_channel_availability.py b/saleor/graphql/channel/tests/test_channel_availability.pyindex dd7d3ec4c6..e48d4627e9 100644--- a/saleor/graphql/channel/tests/test_channel_availability.py+++ b/saleor/graphql/channel/tests/test_channel_availability.py@@ -1,6 +1,10 @@+from unittest import mock+import graphene+from django.utils.functional import SimpleLazyObjectfrom ....channel.error_codes import ChannelErrorCode+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import get_graphql_contentCHANNEL_ACTIVATE_MUTATION = """@@ -45,6 +49,45 @@ def test_channel_activate_mutation(assert data["channel"]["isActive"] is True[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_channel_activate_mutation_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ channel_USD.is_active = False+ channel_USD.save()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ variables = {"id": channel_id}+ # when+ response = staff_api_client.post_graphql(+ CHANNEL_ACTIVATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["channelActivate"]["errors"]+ mocked_webhook_trigger.assert_called_once_with(+ {"id": variables["id"], "is_active": True},+ WebhookEventAsyncType.CHANNEL_STATUS_CHANGED,+ [any_webhook],+ channel_USD,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_channel_activate_mutation_on_activated_channel(permission_manage_channels, staff_api_client, channel_USD):@@ -106,6 +149,43 @@ def test_channel_deactivate_mutation(assert data["channel"]["isActive"] is False[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_channel_deactivate_mutation_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ variables = {"id": channel_id}+ # when+ response = staff_api_client.post_graphql(+ CHANNEL_DEACTIVATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ assert not content["data"]["channelDeactivate"]["errors"]+ mocked_webhook_trigger.assert_called_once_with(+ {"id": variables["id"], "is_active": False},+ WebhookEventAsyncType.CHANNEL_STATUS_CHANGED,+ [any_webhook],+ channel_USD,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_channel_deactivate_mutation_on_deactivated_channel(permission_manage_channels, staff_api_client, channel_USD):@@ -113,8 +193,8 @@ def test_channel_deactivate_mutation_on_deactivated_channel(channel_USD.is_active = Falsechannel_USD.save()channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)-variables = {"id": channel_id}+# whenresponse = staff_api_client.post_graphql(CHANNEL_DEACTIVATE_MUTATION,diff --git a/saleor/graphql/channel/tests/test_channel_create_mutations.py b/saleor/graphql/channel/tests/test_channel_create_mutations.pyindex c41f8e1cd7..463fc0a32b 100644--- a/saleor/graphql/channel/tests/test_channel_create_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_create_mutations.py@@ -1,8 +1,12 @@+from unittest import mock+import graphene+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom ....channel.error_codes import ChannelErrorCodefrom ....channel.models import Channel+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import assert_no_permission, get_graphql_contentCHANNEL_CREATE_MUTATION = """@@ -267,3 +271,53 @@ def test_channel_create_mutation_with_shipping_zones(assert channel_data["currencyCode"] == channel.currency_code == currency_codefor shipping_zone in shipping_zones:shipping_zone.channels.get(slug=slug)++[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_channel_create_mutation_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ permission_manage_channels,+ staff_api_client,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ name = "testName"+ slug = "test_slug"+ currency_code = "USD"+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_CREATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)+ channel = Channel.objects.last()+ data = content["data"]["channelCreate"]++ # then+ assert data["channel"]+ assert not data["errors"]++ mocked_webhook_trigger.assert_called_once_with(+ {"id": graphene.Node.to_global_id("Channel", channel.id)},+ WebhookEventAsyncType.CHANNEL_CREATED,+ [any_webhook],+ channel,+ SimpleLazyObject(lambda: staff_api_client.user),+ )diff --git a/saleor/graphql/channel/tests/test_channel_delete_mutations.py b/saleor/graphql/channel/tests/test_channel_delete_mutations.pyindex da96efad20..0148e57079 100644--- a/saleor/graphql/channel/tests/test_channel_delete_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_delete_mutations.py@@ -1,9 +1,13 @@+from unittest import mock+import graphene+from django.utils.functional import SimpleLazyObjectfrom ....channel.error_codes import ChannelErrorCodefrom ....channel.models import Channelfrom ....checkout.models import Checkoutfrom ....order.models import Order+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import assert_no_permission, get_graphql_contentCHANNEL_DELETE_MUTATION = """@@ -225,3 +229,45 @@ def test_channel_delete_mutation_as_anonymous(# thenassert_no_permission(response)assert Channel.objects.filter(slug=channel_USD.slug).exists()++[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_channel_delete_mutation_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ checkout,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ other_channel_USD,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)+ variables = {"id": channel_id, "input": {"channelId": channel_target_id}}+ assert Checkout.objects.first() is not None++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_DELETE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ get_graphql_content(response)++ # then+ assert not Channel.objects.filter(slug=channel_USD.slug).exists()++ mocked_webhook_trigger.assert_called_once_with(+ {"id": graphene.Node.to_global_id("Channel", channel_USD.id)},+ WebhookEventAsyncType.CHANNEL_DELETED,+ [any_webhook],+ channel_USD,+ SimpleLazyObject(lambda: staff_api_client.user),+ )diff --git a/saleor/graphql/channel/tests/test_channel_update_mutations.py b/saleor/graphql/channel/tests/test_channel_update_mutations.pyindex 0c2eabdedd..8755ed77d9 100644--- a/saleor/graphql/channel/tests/test_channel_update_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_update_mutations.py@@ -1,9 +1,11 @@from unittest.mock import patchimport graphene+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugifyfrom ....channel.error_codes import ChannelErrorCode+from ....webhook.event_types import WebhookEventAsyncTypefrom ...tests.utils import assert_no_permission, get_graphql_contentCHANNEL_UPDATE_MUTATION = """@@ -406,3 +408,49 @@ def test_channel_update_mutation_duplicated_shipping_zone(assert errors[0]["field"] == "shippingZones"assert errors[0]["code"] == ChannelErrorCode.DUPLICATED_INPUT_ITEM.nameassert errors[0]["shippingZones"] == [add_shipping_zone]+++@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_channel_update_mutation_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ name = "newName"+ slug = "new_slug"+ default_country = "FR"+ variables = {+ "id": channel_id,+ "input": {"name": name, "slug": slug, "defaultCountry": default_country},+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=(permission_manage_channels,),+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["channelUpdate"]+ assert not data["errors"]+ assert data["channel"]++ mocked_webhook_trigger.assert_called_once_with(+ {"id": channel_id},+ WebhookEventAsyncType.CHANNEL_UPDATED,+ [any_webhook],+ channel_USD,+ SimpleLazyObject(lambda: staff_api_client.user),+ )diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4438565bb2..5cd2905733 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1105,6 +1105,18 @@ enum WebhookEventTypeEnum {"""A category is deleted."""CATEGORY_DELETED+ """A new channel created."""+ CHANNEL_CREATED++ """A channel is updated."""+ CHANNEL_UPDATED++ """A channel is deleted."""+ CHANNEL_DELETED++ """A channel status is changed."""+ CHANNEL_STATUS_CHANGED+"""A new order is placed."""ORDER_CREATED@@ -1280,6 +1292,18 @@ enum WebhookEventTypeAsyncEnum {"""A category is deleted."""CATEGORY_DELETED+ """A new channel created."""+ CHANNEL_CREATED++ """A channel is updated."""+ CHANNEL_UPDATED++ """A channel is deleted."""+ CHANNEL_DELETED++ """A channel status is changed."""+ CHANNEL_STATUS_CHANGED+"""A new order is placed."""ORDER_CREATED@@ -1760,6 +1784,10 @@ enum WebhookSampleEventTypeEnum {CATEGORY_CREATEDCATEGORY_UPDATEDCATEGORY_DELETED+ CHANNEL_CREATED+ CHANNEL_UPDATED+ CHANNEL_DELETED+ CHANNEL_STATUS_CHANGEDORDER_CREATEDORDER_CONFIRMEDORDER_FULLY_PAID@@ -16589,7 +16617,7 @@ type Subscription {event: Event}-union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | 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 | 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 | TranslationUpdatedtype CategoryCreated {"""@@ -16612,6 +16640,34 @@ type CategoryDeleted {category: Category}+type ChannelCreated {+ """+ New in Saleor 3.2. Look up a channel. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ channel: Channel+}++type ChannelUpdated {+ """+ New in Saleor 3.2. Look up a channel. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ channel: Channel+}++type ChannelDeleted {+ """+ New in Saleor 3.2. Look up a channel. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ channel: Channel+}++type ChannelStatusChanged {+ """+ New in Saleor 3.2. Look up a channel. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ channel: Channel+}+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.pyindex 6c1c2dcdb3..bbf9eb2a7c 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -26,6 +26,10 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.CATEGORY_CREATED: "A new category created.",WebhookEventAsyncType.CATEGORY_UPDATED: "A category is updated.",WebhookEventAsyncType.CATEGORY_DELETED: "A category is deleted.",+ WebhookEventAsyncType.CHANNEL_CREATED: "A new channel created.",+ WebhookEventAsyncType.CHANNEL_UPDATED: "A channel is updated.",+ WebhookEventAsyncType.CHANNEL_DELETED: "A channel is deleted.",+ WebhookEventAsyncType.CHANNEL_STATUS_CHANGED: "A channel status is changed.",WebhookEventAsyncType.CHECKOUT_CREATED: "A new checkout is created.",WebhookEventAsyncType.CHECKOUT_UPDATED: checkout_updated_event_enum_description,WebhookEventAsyncType.COLLECTION_CREATED: "A new collection is created.",diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.pyindex b83a5b4159..1f28d33b18 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -57,6 +57,34 @@ class CategoryDeleted(ObjectType, CategoryBase):...+class ChannelBase(AbstractType):+ channel = graphene.Field(+ "saleor.graphql.channel.types.Channel",+ description=f"{ADDED_IN_32} Look up a channel. {PREVIEW_FEATURE}",+ )++ @staticmethod+ def resolve_channel(root, info):+ _, channel = root+ return channel+++class ChannelCreated(ObjectType, ChannelBase):+ ...+++class ChannelUpdated(ObjectType, ChannelBase):+ ...+++class ChannelDeleted(ObjectType, ChannelBase):+ ...+++class ChannelStatusChanged(ObjectType, ChannelBase):+ ...++class OrderBase(AbstractType):order = graphene.Field("saleor.graphql.order.types.Order",@@ -471,6 +499,10 @@ class Event(Union):CategoryCreated,CategoryUpdated,CategoryDeleted,+ ChannelCreated,+ ChannelUpdated,+ ChannelDeleted,+ ChannelStatusChanged,OrderCreated,OrderUpdated,OrderConfirmed,@@ -522,6 +554,10 @@ class Event(Union):WebhookEventAsyncType.CATEGORY_CREATED: CategoryCreated,WebhookEventAsyncType.CATEGORY_UPDATED: CategoryUpdated,WebhookEventAsyncType.CATEGORY_DELETED: CategoryDeleted,+ WebhookEventAsyncType.CHANNEL_CREATED: ChannelCreated,+ WebhookEventAsyncType.CHANNEL_UPDATED: ChannelUpdated,+ WebhookEventAsyncType.CHANNEL_DELETED: ChannelDeleted,+ WebhookEventAsyncType.CHANNEL_STATUS_CHANGED: ChannelStatusChanged,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.pyindex 062c17a8ca..de41737761 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -253,6 +253,30 @@ class BasePlugin:# updated.category_updated: Callable[["Category", None], None]+ # Trigger when channel is created.+ #+ # Overwrite this method if you need to trigger specific logic after a channel is+ # created.+ channel_created: Callable[["Channel", None], None]++ # Trigger when channel is deleted.+ #+ # Overwrite this method if you need to trigger specific logic after a channel is+ # deleted.+ channel_deleted: Callable[["Channel", None], None]++ # Trigger when channel is updated.+ #+ # Overwrite this method if you need to trigger specific logic after a channel is+ # updated.+ channel_updated: Callable[["Channel", None], None]++ # Trigger when channel status is changed.+ #+ # Overwrite this method if you need to trigger specific logic after a channel+ # status is changed.+ channel_status_changed: Callable[["Channel", None], None]+change_user_address: Callable[["Address", Union[str, NoneType], Union["User", NoneType], "Address"], "Address"]diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 2d8e155229..520834ad9e 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -799,6 +799,24 @@ class PluginsManager(PaymentInterface):default_value = Nonereturn self.__run_method_on_plugins("category_deleted", default_value, category)+ def channel_created(self, channel: "Channel"):+ default_value = None+ return self.__run_method_on_plugins("channel_created", default_value, channel)++ def channel_updated(self, channel: "Channel"):+ default_value = None+ return self.__run_method_on_plugins("channel_updated", default_value, channel)++ def channel_deleted(self, channel: "Channel"):+ default_value = None+ return self.__run_method_on_plugins("channel_deleted", default_value, channel)++ def channel_status_changed(self, channel: "Channel"):+ default_value = None+ return self.__run_method_on_plugins(+ "channel_status_changed", default_value, channel+ )+def shipping_price_created(self, shipping_method: "ShippingMethod"):default_value = Nonereturn self.__run_method_on_plugins(diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 9d039d2739..4d3b5fc68c 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -50,6 +50,7 @@ from .utils import (if TYPE_CHECKING:from ...account.models import User+ from ...channel.models import Channelfrom ...checkout.models import Checkoutfrom ...discount.models import Salefrom ...graphql.discount.mutations import NodeCatalogueInfo@@ -114,6 +115,49 @@ class WebhookPlugin(BasePlugin):payload, event_type, webhooks, category, self.requestor)+ def channel_created(self, channel: "Channel", previous_value: None) -> None:+ if not self.active:+ return previous_value+ event_type = WebhookEventAsyncType.CHANNEL_CREATED+ if webhooks := get_webhooks_for_event(event_type):+ payload = {"id": graphene.Node.to_global_id("Channel", channel.id)}+ trigger_webhooks_async(+ payload, event_type, webhooks, channel, self.requestor+ )++ def channel_updated(self, channel: "Channel", previous_value: None) -> None:+ if not self.active:+ return previous_value+ event_type = WebhookEventAsyncType.CHANNEL_UPDATED+ if webhooks := get_webhooks_for_event(event_type):+ payload = {"id": graphene.Node.to_global_id("Channel", channel.id)}+ trigger_webhooks_async(+ payload, event_type, webhooks, channel, self.requestor+ )++ def channel_deleted(self, channel: "Channel", previous_value: None) -> None:+ if not self.active:+ return previous_value+ event_type = WebhookEventAsyncType.CHANNEL_DELETED+ if webhooks := get_webhooks_for_event(event_type):+ payload = {"id": graphene.Node.to_global_id("Channel", channel.id)}+ trigger_webhooks_async(+ payload, event_type, webhooks, channel, self.requestor+ )++ def channel_status_changed(self, channel: "Channel", previous_value: None) -> None:+ if not self.active:+ return previous_value+ event_type = WebhookEventAsyncType.CHANNEL_STATUS_CHANGED+ if webhooks := get_webhooks_for_event(event_type):+ payload = {+ "id": graphene.Node.to_global_id("Channel", channel.id),+ "is_active": channel.is_active,+ }+ trigger_webhooks_async(+ payload, event_type, webhooks, channel, self.requestor+ )+def order_created(self, order: "Order", previous_value: Any) -> Any:if not self.active:return previous_valuediff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 4ccab36f03..f1e4cf8f1a 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -125,6 +125,7 @@ def trigger_webhooks_async("""regular_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)deliveries = []+if regular_webhooks:payload = EventPayload.objects.create(payload=data)deliveries.extend(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex 8f82dcdd80..6fe71ff2fd 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -79,6 +79,88 @@ def subscription_category_deleted_webhook(subscription_webhook):)+CHANNEL_CREATED_SUBSCRIPTION_QUERY = """+ subscription{+ event{+ ...on ChannelCreated{+ channel{+ id+ }+ }+ }+ }+"""+++def subscription_channel_created_webhook(subscription_webhook):+ return subscription_webhook(+ CHANNEL_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CHANNEL_CREATED+ )+++CHANNEL_UPDATED_SUBSCRIPTION_QUERY = """+ subscription{+ event{+ ...on ChannelUpdated{+ channel{+ id+ }+ }+ }+ }+"""+++def subscription_channel_updated_webhook(subscription_webhook):+ return subscription_webhook(+ CHANNEL_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CHANNEL_UPDATED+ )+++CHANNEL_DELETED_SUBSCRIPTION_QUERY = """+ subscription{+ event{+ ...on ChannelDeleted{+ channel{+ id+ }+ }+ }+ }+"""+++def subscription_channel_deleted_webhook(subscription_webhook):+ return subscription_webhook(+ CHANNEL_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CHANNEL_DELETED+ )+++CHANNEL_STATUS_CHANGED_SUBSCRIPTION_QUERY = """+ subscription{+ event{+ ...on ChannelStatusChanged{+ channel{+ id+ isActive+ }+ }+ }+ }+"""+++def subscription_channel_status_changed_webhook(subscription_webhook):+ return subscription_webhook(+ CHANNEL_STATUS_CHANGED_SUBSCRIPTION_QUERY,+ WebhookEventAsyncType.CHANNEL_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.pyindex a6c23c9584..fbb0853744 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@@ -2,7 +2,9 @@ import jsonfrom unittest.mock import patchimport graphene+import pytest+from .....channel.models import Channelfrom .....graphql.webhook.subscription_payload import validate_subscription_queryfrom .....product.models import Categoryfrom .....shipping.models import ShippingMethod, ShippingZone@@ -66,6 +68,87 @@ def test_category_deleted(category, subscription_category_deleted_webhook):assert deliveries[0].webhook == webhooks[0]+def test_channel_created(channel_USD, subscription_channel_created_webhook):+ # given+ webhooks = [subscription_channel_created_webhook]+ event_type = WebhookEventAsyncType.CHANNEL_CREATED+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, channel_USD, webhooks)++ # then+ expected_payload = json.dumps({"channel": {"id": channel_id}, "meta": None})+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_channel_updated(channel_USD, subscription_channel_updated_webhook):+ # given+ webhooks = [subscription_channel_updated_webhook]+ event_type = WebhookEventAsyncType.CHANNEL_UPDATED+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, channel_USD, webhooks)++ # then+ expected_payload = json.dumps({"channel": {"id": channel_id}, "meta": None})+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_channel_deleted(channel_USD, subscription_channel_deleted_webhook):+ # given+ webhooks = [subscription_channel_deleted_webhook]++ channel_query = Channel.objects.filter(pk=channel_USD.id)+ channel_instances = [channel for channel in channel_query]+ channel_query.delete()++ event_type = WebhookEventAsyncType.CHANNEL_DELETED+ channel_id = graphene.Node.to_global_id("Channel", channel_instances[0].id)++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, channel_instances[0], webhooks+ )++ # then+ expected_payload = json.dumps({"channel": {"id": channel_id}, "meta": None})+ assert channel_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_channel_status_changed(+ status, channel_USD, subscription_channel_status_changed_webhook+):+ # given+ webhooks = [subscription_channel_status_changed_webhook]++ channel_USD.is_active = status+ channel_USD.save(update_fields=["is_active"])++ event_type = WebhookEventAsyncType.CHANNEL_STATUS_CHANGED+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)++ # when+ deliveries = create_deliveries_for_subscriptions(event_type, channel_USD, webhooks)++ # then+ expected_payload = json.dumps(+ {"channel": {"id": channel_id, "isActive": status}, "meta": None}+ )+ 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/webhook/event_types.py b/saleor/webhook/event_types.pyindex 2d766f787e..eeaed38e32 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -1,5 +1,6 @@from ..core.permissions import (AccountPermissions,+ ChannelPermissions,CheckoutPermissions,DiscountPermissions,OrderPermissions,@@ -18,6 +19,11 @@ class WebhookEventAsyncType:CATEGORY_UPDATED = "category_updated"CATEGORY_DELETED = "category_deleted"+ CHANNEL_CREATED = "channel_created"+ CHANNEL_UPDATED = "channel_updated"+ CHANNEL_DELETED = "channel_deleted"+ CHANNEL_STATUS_CHANGED = "channel_status_changed"+ORDER_CREATED = "order_created"ORDER_CONFIRMED = "order_confirmed"ORDER_FULLY_PAID = "order_fully_paid"@@ -83,6 +89,10 @@ class WebhookEventAsyncType:CATEGORY_CREATED: "Category created",CATEGORY_UPDATED: "Category updated",CATEGORY_DELETED: "Category deleted",+ CHANNEL_CREATED: "Channel created",+ CHANNEL_UPDATED: "Channel updated",+ CHANNEL_DELETED: "Channel deleted",+ CHANNEL_STATUS_CHANGED: "Channel status changed",ORDER_CREATED: "Order created",ORDER_CONFIRMED: "Order confirmed",ORDER_FULLY_PAID: "Order paid",@@ -134,6 +144,10 @@ class WebhookEventAsyncType:(CATEGORY_CREATED, DISPLAY_LABELS[CATEGORY_CREATED]),(CATEGORY_UPDATED, DISPLAY_LABELS[CATEGORY_UPDATED]),(CATEGORY_DELETED, DISPLAY_LABELS[CATEGORY_DELETED]),+ (CHANNEL_CREATED, DISPLAY_LABELS[CHANNEL_CREATED]),+ (CHANNEL_UPDATED, DISPLAY_LABELS[CHANNEL_UPDATED]),+ (CHANNEL_DELETED, DISPLAY_LABELS[CHANNEL_DELETED]),+ (CHANNEL_STATUS_CHANGED, DISPLAY_LABELS[CHANNEL_STATUS_CHANGED]),(ORDER_CREATED, DISPLAY_LABELS[ORDER_CREATED]),(ORDER_CONFIRMED, DISPLAY_LABELS[ORDER_CONFIRMED]),(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),@@ -186,6 +200,10 @@ class WebhookEventAsyncType:CATEGORY_CREATED: ProductPermissions.MANAGE_PRODUCTS,CATEGORY_UPDATED: ProductPermissions.MANAGE_PRODUCTS,CATEGORY_DELETED: ProductPermissions.MANAGE_PRODUCTS,+ CHANNEL_CREATED: ChannelPermissions.MANAGE_CHANNELS,+ CHANNEL_UPDATED: ChannelPermissions.MANAGE_CHANNELS,+ CHANNEL_DELETED: ChannelPermissions.MANAGE_CHANNELS,+ CHANNEL_STATUS_CHANGED: ChannelPermissions.MANAGE_CHANNELS,ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,@@ -308,6 +326,10 @@ SUBSCRIBABLE_EVENTS = [WebhookEventAsyncType.CATEGORY_CREATED,WebhookEventAsyncType.CATEGORY_UPDATED,WebhookEventAsyncType.CATEGORY_DELETED,+ WebhookEventAsyncType.CHANNEL_CREATED,+ WebhookEventAsyncType.CHANNEL_UPDATED,+ WebhookEventAsyncType.CHANNEL_DELETED,+ WebhookEventAsyncType.CHANNEL_STATUS_CHANGED,WebhookEventAsyncType.ORDER_CREATED,WebhookEventAsyncType.ORDER_UPDATED,WebhookEventAsyncType.ORDER_CONFIRMED,