Skip to content

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

New events related to apps changes. (#9698)

SzymJb5e414c98a15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4595725d69..da12d73e08 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,11 @@ All notable, unreleased changes to this project will be documented in this file.
- add new webhook event:
- `TRANSACTION_ACTION_REQUEST`
+#### Saleor Apps
+- Add webhooks `MENU_CREATED`, `MENU_UPDATED`, `MENU_DELETED`, `MENU_ITEM_CREATED`, `MENU_ITEM_UPDATED`, `MENU_ITEM_DELETED` - #9651 by @SzymJ
+- Add webhooks `VOUCHER_CREATED`, `VOUCHER_UPDATED`, `VOUCHER_DELETED` - #9657 by @SzymJ
+- Add webhooks `APP_CREATED`, `APP_UPDATED`, `APP_DELETED`, `APP_STATUS_CHANGED` - #9698 by @SzymJ
+
# 3.3.1
- Drop manual calls to emit post_migrate in migrations (#9647) (b32308802)
@@ -66,8 +71,6 @@ All notable, unreleased changes to this project will be documented in this file.
- Optimize stock warehouse resolver performance (955489bff) by @tomaszszymanski129
- Improve shipping zone filters performance (#9540) (7841ec536) by @tomaszszymanski129
-#### Saleor Apps
-- Add webhooks `MENU_CREATED`, `MENU_UPDATED`, `MENU_DELETED`, `MENU_ITEM_CREATED`, `MENU_ITEM_UPDATED`, `MENU_ITEM_DELETED` - #9651 by @SzymJ
# 3.2.0
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 63899cd779..215a94018d 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -1,7 +1,9 @@
import requests
+from django.conf import settings
from django.contrib.sites.models import Site
from ..core.permissions import get_permission_names
+from ..plugins.manager import PluginsManager
from .manifest_validations import clean_manifest_data
from .models import App, AppExtension, AppInstallation
from .types import AppExtensionTarget, AppType
@@ -24,10 +26,7 @@ def send_app_token(target_url: str, token: str):
response.raise_for_status()
-def install_app(
- app_installation: AppInstallation,
- activate: bool = False,
-):
+def install_app(app_installation: AppInstallation, activate: bool = False):
response = requests.get(app_installation.manifest_url, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
assigned_permissions = app_installation.permissions.all()
@@ -69,4 +68,5 @@ def install_app(
except requests.RequestException as e:
app.delete()
raise e
+ PluginsManager(plugins=settings.PLUGINS).app_created(app)
return app, token
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index d5984cb21a..8eb856bfb5 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -1,9 +1,11 @@
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
+import graphene
import pytest
import requests
from django.core.exceptions import ValidationError
+from ...webhook.event_types import WebhookEventAsyncType
from ..installation_utils import install_app
from ..models import App
from ..types import AppExtensionMount, AppExtensionTarget
@@ -30,6 +32,48 @@ def test_install_app_created_app(
assert list(app.permissions.all()) == [permission_manage_products]
+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_install_app_created_app_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ app_manifest,
+ app_installation,
+ monkeypatch,
+ permission_manage_products,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())
+
+ app_installation.permissions.set([permission_manage_products])
+
+ # when
+ app, _ = install_app(app_installation, activate=True)
+
+ # then
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": graphene.Node.to_global_id("App", app.id),
+ "is_active": app.is_active,
+ "name": app.name,
+ },
+ WebhookEventAsyncType.APP_CREATED,
+ [any_webhook],
+ app,
+ None,
+ )
+
+
def test_install_app_with_extension(
app_manifest,
app_installation,
diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.py
index fa6b883e5b..d5a426f43f 100644
--- a/saleor/graphql/app/mutations.py
+++ b/saleor/graphql/app/mutations.py
@@ -177,6 +177,7 @@ class AppCreate(ModelMutation):
cls._save_m2m(info, instance, cleaned_input)
response = cls.success_response(instance)
response.auth_token = auth_token
+ info.context.plugins.app_created(instance)
return response
@classmethod
@@ -220,6 +221,10 @@ class AppUpdate(ModelMutation):
ensure_can_manage_permissions(requestor, permissions)
return cleaned_input
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.app_updated(instance)
+
class AppDelete(ModelDeleteMutation):
class Arguments:
@@ -243,6 +248,10 @@ class AppDelete(ModelDeleteMutation):
code = AppErrorCode.OUT_OF_SCOPE_APP.value
raise ValidationError({"id": ValidationError(msg, code=code)})
+ @classmethod
+ def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.app_deleted(instance)
+
class AppActivate(ModelMutation):
class Arguments:
@@ -261,6 +270,7 @@ class AppActivate(ModelMutation):
app = cls.get_instance(info, **data)
app.is_active = True
cls.save(info, app, cleaned_input=None)
+ info.context.plugins.app_status_changed(app)
return cls.success_response(app)
@@ -281,6 +291,7 @@ class AppDeactivate(ModelMutation):
app = cls.get_instance(info, **data)
app.is_active = False
cls.save(info, app, cleaned_input=None)
+ info.context.plugins.app_status_changed(app)
return cls.success_response(app)
diff --git a/saleor/graphql/app/tests/mutations/test_app_activate.py b/saleor/graphql/app/tests/mutations/test_app_activate.py
index 48db014149..9fb1310e00 100644
--- a/saleor/graphql/app/tests/mutations/test_app_activate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_activate.py
@@ -1,6 +1,10 @@
+from unittest import mock
+
import graphene
+from django.utils.functional import SimpleLazyObject
from .....app.models import App
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
APP_ACTIVATE_MUTATION = """
@@ -42,6 +46,51 @@ def test_activate_app(app, staff_api_client, permission_manage_apps):
assert app.is_active
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_activate_app_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ app,
+ staff_api_client,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ app.is_active = False
+ app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id("App", app.id),
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ APP_ACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_apps,),
+ )
+ app.refresh_from_db()
+
+ # then
+ assert app.is_active
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": variables["id"],
+ "is_active": app.is_active,
+ "name": app.name,
+ },
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ [any_webhook],
+ app,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_activate_app_by_app(app, app_api_client, permission_manage_apps):
# given
app = App.objects.create(name="Sample app objects", is_active=False)
diff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.py
index 7dbc88e4f1..da3577e089 100644
--- a/saleor/graphql/app/tests/mutations/test_app_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_create.py
@@ -1,5 +1,11 @@
+from unittest import mock
+
+import graphene
+from django.utils.functional import SimpleLazyObject
+
from .....app.error_codes import AppErrorCode
from .....app.models import App
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.enums import PermissionEnum
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -61,6 +67,51 @@ def test_app_create_mutation(
assert default_token[-4:] == app.tokens.get().token_last_4
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_create_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ permission_manage_apps,
+ permission_manage_products,
+ staff_api_client,
+ staff_user,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_user.user_permissions.add(permission_manage_products)
+
+ variables = {
+ "name": "Trigger Test",
+ "permissions": [PermissionEnum.MANAGE_PRODUCTS.name],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_CREATE_MUTATION, variables=variables, permissions=(permission_manage_apps,)
+ )
+ content = get_graphql_content(response)
+ app = App.objects.get(name=variables["name"])
+
+ # then
+ assert content["data"]["appCreate"]["app"]
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": graphene.Node.to_global_id("App", app.id),
+ "is_active": app.is_active,
+ "name": app.name,
+ },
+ WebhookEventAsyncType.APP_CREATED,
+ [any_webhook],
+ app,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_app_is_not_allowed_to_call_create_mutation_for_app(
permission_manage_apps,
permission_manage_products,
diff --git a/saleor/graphql/app/tests/mutations/test_app_deactivate.py b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
index 2aa09332ce..caf7e84c29 100644
--- a/saleor/graphql/app/tests/mutations/test_app_deactivate.py
+++ b/saleor/graphql/app/tests/mutations/test_app_deactivate.py
@@ -1,6 +1,10 @@
+from unittest import mock
+
import graphene
+from django.utils.functional import SimpleLazyObject
from .....app.models import App
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import assert_no_permission, get_graphql_content
APP_DEACTIVATE_MUTATION = """
@@ -42,6 +46,51 @@ def test_deactivate_app(app, staff_api_client, permission_manage_apps):
assert not app.is_active
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_deactivate_app_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ app,
+ staff_api_client,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ app.is_active = True
+ app.save()
+
+ variables = {
+ "id": graphene.Node.to_global_id("App", app.id),
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ APP_DEACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_apps,),
+ )
+ app.refresh_from_db()
+
+ # then
+ assert not app.is_active
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": variables["id"],
+ "is_active": app.is_active,
+ "name": app.name,
+ },
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ [any_webhook],
+ app,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_deactivate_app_by_app(app, app_api_client, permission_manage_apps):
# given
app = App.objects.create(name="Sample app objects", is_active=True)
diff --git a/saleor/graphql/app/tests/mutations/test_app_delete.py b/saleor/graphql/app/tests/mutations/test_app_delete.py
index 08f440a743..612d12bedf 100644
--- a/saleor/graphql/app/tests/mutations/test_app_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_delete.py
@@ -1,7 +1,11 @@
+from unittest import mock
+
import graphene
+from django.utils.functional import SimpleLazyObject
from .....app.error_codes import AppErrorCode
from .....app.models import App
+from .....webhook.event_types import WebhookEventAsyncType
from ....tests.utils import get_graphql_content
APP_DELETE_MUTATION = """
@@ -44,6 +48,50 @@ def test_app_delete(
assert not App.objects.filter(id=app.id)
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_delete_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ staff_user,
+ app,
+ permission_manage_orders,
+ permission_manage_apps,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ app.permissions.add(permission_manage_orders)
+ staff_user.user_permissions.add(permission_manage_orders)
+ app_global_id = graphene.Node.to_global_id("App", app.id)
+
+ variables = {"id": app_global_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_DELETE_MUTATION, variables=variables, permissions=(permission_manage_apps,)
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["appDelete"]["app"]
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": app_global_id,
+ "is_active": app.is_active,
+ "name": app.name,
+ },
+ WebhookEventAsyncType.APP_DELETED,
+ [any_webhook],
+ app,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_app_delete_for_app(
app_api_client,
permission_manage_orders,
diff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.py
index a2d4313e5f..eb79e016f2 100644
--- a/saleor/graphql/app/tests/mutations/test_app_update.py
+++ b/saleor/graphql/app/tests/mutations/test_app_update.py
@@ -1,7 +1,11 @@
+from unittest import mock
+
import graphene
+from django.utils.functional import SimpleLazyObject
from .....app.error_codes import AppErrorCode
from .....app.models import App, AppToken
+from .....webhook.event_types import WebhookEventAsyncType
from ....core.enums import PermissionEnum
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -71,6 +75,57 @@ def test_app_update_mutation(
}
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_app_update_trigger_mutation(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ app_with_token,
+ permission_manage_apps,
+ permission_manage_products,
+ permission_manage_users,
+ staff_api_client,
+ staff_user,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
+ app_global_id = graphene.Node.to_global_id("App", app_with_token.id)
+
+ variables = {
+ "id": app_global_id,
+ "permissions": [
+ PermissionEnum.MANAGE_PRODUCTS.name,
+ PermissionEnum.MANAGE_USERS.name,
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_UPDATE_MUTATION, variables=variables, permissions=(permission_manage_apps,)
+ )
+ content = get_graphql_content(response)
+ app_with_token.refresh_from_db()
+
+ # then
+ assert content["data"]["appUpdate"]["app"]
+ mocked_webhook_trigger.assert_called_once_with(
+ {
+ "id": variables["id"],
+ "is_active": app_with_token.is_active,
+ "name": app_with_token.name,
+ },
+ WebhookEventAsyncType.APP_UPDATED,
+ [any_webhook],
+ app_with_token,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_app_update_mutation_for_app(
permission_manage_apps,
permission_manage_products,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 18435b56f5..a04c75f060 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1318,6 +1318,18 @@ enum WebhookEventTypeEnum {
"""All the events."""
ANY_EVENTS
+ """A new app created."""
+ APP_CREATED
+
+ """An app updated."""
+ APP_UPDATED
+
+ """An app deleted."""
+ APP_DELETED
+
+ """An app status is changed."""
+ APP_STATUS_CHANGED
+
"""A new category created."""
CATEGORY_CREATED
@@ -1545,6 +1557,18 @@ enum WebhookEventTypeAsyncEnum {
"""All the events."""
ANY_EVENTS
+ """A new app created."""
+ APP_CREATED
+
+ """An app updated."""
+ APP_UPDATED
+
+ """An app deleted."""
+ APP_DELETED
+
+ """An app status is changed."""
+ APP_STATUS_CHANGED
+
"""A new category created."""
CATEGORY_CREATED
@@ -2179,6 +2203,10 @@ scalar JSONString
"""An enumeration."""
enum WebhookSampleEventTypeEnum {
+ APP_CREATED
+ APP_UPDATED
+ APP_DELETED
+ APP_STATUS_CHANGED
CATEGORY_CREATED
CATEGORY_UPDATED
CATEGORY_DELETED
@@ -20050,7 +20078,51 @@ type Subscription {
event: Event
}
-union Event = CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | MenuCreated | MenuUpdated | MenuDeleted | MenuItemCreated | MenuItemUpdated | MenuItemDeleted | 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 | TransactionActionRequest | TranslationCreated | TranslationUpdated | VoucherCreated | VoucherUpdated | VoucherDeleted
+union Event = AppCreated | AppUpdated | AppDeleted | AppStatusChanged | CategoryCreated | CategoryUpdated | CategoryDeleted | ChannelCreated | ChannelUpdated | ChannelDeleted | ChannelStatusChanged | GiftCardCreated | GiftCardUpdated | GiftCardDeleted | GiftCardStatusChanged | MenuCreated | MenuUpdated | MenuDeleted | MenuItemCreated | MenuItemUpdated | MenuItemDeleted | 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 | TransactionActionRequest | TranslationCreated | TranslationUpdated | VoucherCreated | VoucherUpdated | VoucherDeleted
+
+type AppCreated {
+ """
+ Look up a app.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ app: App
+}
+
+type AppUpdated {
+ """
+ Look up a app.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ app: App
+}
+
+type AppDeleted {
+ """
+ Look up a app.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ app: App
+}
+
+type AppStatusChanged {
+ """
+ Look up a app.
+
+ Added in Saleor 3.4.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ app: App
+}
type CategoryCreated {
"""
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index f7fa51a2f1..1a24584b3f 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -23,6 +23,10 @@ order_updated_event_enum_description = (
WEBHOOK_EVENT_DESCRIPTION = {
+ WebhookEventAsyncType.APP_CREATED: "A new app created.",
+ WebhookEventAsyncType.APP_UPDATED: "An app updated.",
+ WebhookEventAsyncType.APP_DELETED: "An app deleted.",
+ WebhookEventAsyncType.APP_STATUS_CHANGED: "An app status is changed.",
WebhookEventAsyncType.CATEGORY_CREATED: "A new category created.",
WebhookEventAsyncType.CATEGORY_UPDATED: "A category is updated.",
WebhookEventAsyncType.CATEGORY_DELETED: "A category is deleted.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 45aa45bd36..9a55a2b130 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -38,6 +38,34 @@ TRANSLATIONS_TYPES_MAP = {
}
+class AppBase(AbstractType):
+ app = graphene.Field(
+ "saleor.graphql.app.types.App",
+ description="Look up a app." + ADDED_IN_34 + PREVIEW_FEATURE,
+ )
+
+ @staticmethod
+ def resolve_app(root, _info):
+ _, app = root
+ return app
+
+
+class AppCreated(ObjectType, AppBase):
+ ...
+
+
+class AppUpdated(ObjectType, AppBase):
+ ...
+
+
+class AppDeleted(ObjectType, AppBase):
+ ...
+
+
+class AppStatusChanged(ObjectType, AppBase):
+ ...
+
+
class CategoryBase(AbstractType):
category = graphene.Field(
"saleor.graphql.product.types.Category",
@@ -651,6 +679,10 @@ class VoucherDeleted(ObjectType, VoucherBase):
class Event(Union):
class Meta:
types = (
+ AppCreated,
+ AppUpdated,
+ AppDeleted,
+ AppStatusChanged,
CategoryCreated,
CategoryUpdated,
CategoryDeleted,
@@ -720,6 +752,10 @@ class Event(Union):
@classmethod
def get_type(cls, object_type: str):
types = {
+ WebhookEventAsyncType.APP_CREATED: AppCreated,
+ WebhookEventAsyncType.APP_UPDATED: AppUpdated,
+ WebhookEventAsyncType.APP_DELETED: AppDeleted,
+ WebhookEventAsyncType.APP_STATUS_CHANGED: AppStatusChanged,
WebhookEventAsyncType.CATEGORY_CREATED: CategoryCreated,
WebhookEventAsyncType.CATEGORY_UPDATED: CategoryUpdated,
WebhookEventAsyncType.CATEGORY_DELETED: CategoryDeleted,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 84db0db4a5..ad43270ff4 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -28,6 +28,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from ..account.models import Address, User
+ from ..app.models import App
from ..channel.models import Channel
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
@@ -132,6 +133,30 @@ class BasePlugin:
def __str__(self):
return self.PLUGIN_NAME
+ # Trigger when app is created.
+ #
+ # Overwrite this method if you need to trigger specific logic after an app is
+ # created.
+ app_created: Callable[["App", None], None]
+
+ # Trigger when app is deleted.
+ #
+ # Overwrite this method if you need to trigger specific logic after an app is
+ # deleted.
+ app_deleted: Callable[["App", None], None]
+
+ # Trigger when app is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after an app is
+ # updated.
+ app_updated: Callable[["App", None], None]
+
+ # Trigger when channel status is changed.
+ #
+ # Overwrite this method if you need to trigger specific logic after an app
+ # status is changed.
+ app_status_changed: Callable[["App", None], None]
+
# Apply taxes to the product price based on the customer country.
#
# Overwrite this method if you want to show products with taxes.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index fa45a2cc92..2896c4957f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -39,6 +39,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from ..account.models import Address, User
+ from ..app.models import App
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..core.middleware import Requestor
@@ -801,6 +802,22 @@ class PluginsManager(PaymentInterface):
channel_slug=channel_slug,
)
+ def app_created(self, app: "App"):
+ default_value = None
+ return self.__run_method_on_plugins("app_created", default_value, app)
+
+ def app_updated(self, app: "App"):
+ default_value = None
+ return self.__run_method_on_plugins("app_updated", default_value, app)
+
+ def app_deleted(self, app: "App"):
+ default_value = None
+ return self.__run_method_on_plugins("app_deleted", default_value, app)
+
+ def app_status_changed(self, app: "App"):
+ default_value = None
+ return self.__run_method_on_plugins("app_status_changed", default_value, app)
+
def category_created(self, category: "Category"):
default_value = None
return self.__run_method_on_plugins("category_created", default_value, category)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c1edf7b947..17a4f3cb4c 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -93,6 +93,35 @@ class WebhookPlugin(BasePlugin):
super().__init__(*args, **kwargs)
self.active = True
+ def _trigger_app_event(self, event_type, app):
+ if webhooks := get_webhooks_for_event(event_type):
+ payload = {
+ "id": graphene.Node.to_global_id("App", app.id),
+ "is_active": app.is_active,
+ "name": app.name,
+ }
+ trigger_webhooks_async(payload, event_type, webhooks, app, self.requestor)
+
+ def app_created(self, app: "App", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_app_event(WebhookEventAsyncType.APP_CREATED, app)
+
+ def app_updated(self, app: "App", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_app_event(WebhookEventAsyncType.APP_UPDATED, app)
+
+ def app_deleted(self, app: "App", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_app_event(WebhookEventAsyncType.APP_DELETED, app)
+
+ def app_status_changed(self, app: "App", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_app_event(WebhookEventAsyncType.APP_STATUS_CHANGED, app)
+
def category_created(self, category: "Category", previous_value: None) -> None:
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 09058c0001..beda8c289a 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -19,6 +19,109 @@ def subscription_webhook(webhook_app):
return fun
+APP_DETAILS_FRAGMENT = """
+ fragment AppDetails on App{
+ id
+ isActive
+ name
+ appUrl
+ }
+"""
+
+
+APP_CREATED_SUBSCRIPTION_QUERY = (
+ APP_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on AppCreated{
+ app{
+ ...AppDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_app_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ APP_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.APP_CREATED
+ )
+
+
+APP_UPDATED_SUBSCRIPTION_QUERY = (
+ APP_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on AppUpdated{
+ app{
+ ...AppDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_app_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ APP_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.APP_UPDATED
+ )
+
+
+APP_DELETED_SUBSCRIPTION_QUERY = (
+ APP_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on AppDeleted{
+ app{
+ ...AppDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_app_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ APP_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.APP_DELETED
+ )
+
+
+APP_STATUS_CHANGED_SUBSCRIPTION_QUERY = (
+ APP_DETAILS_FRAGMENT
+ + """
+ subscription{
+ event{
+ ...on AppStatusChanged{
+ app{
+ ...AppDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+
+def subscription_app_status_changed_webhook(subscription_webhook):
+ return subscription_webhook(
+ APP_STATUS_CHANGED_SUBSCRIPTION_QUERY,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
+ )
+
+
CATEGORY_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 951c083a1e..7fb43b98a3 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
@@ -14,6 +14,94 @@ from .....webhook.event_types import WebhookEventAsyncType
from ...tasks import create_deliveries_for_subscriptions, logger
+def generate_expected_payload_for_app(app, app_global_id):
+ return json.dumps(
+ {
+ "app": {
+ "id": app_global_id,
+ "isActive": app.is_active,
+ "name": app.name,
+ "appUrl": app.app_url,
+ },
+ "meta": None,
+ }
+ )
+
+
+def test_app_created(app, subscription_app_created_webhook):
+ # given
+ webhooks = [subscription_app_created_webhook]
+ event_type = WebhookEventAsyncType.APP_CREATED
+ app_id = graphene.Node.to_global_id("App", app.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, app, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_app(app, app_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_app_updated(app, subscription_app_updated_webhook):
+ # given
+ webhooks = [subscription_app_updated_webhook]
+ event_type = WebhookEventAsyncType.APP_UPDATED
+ gift_card_id = graphene.Node.to_global_id("App", app.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, app, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_app(app, gift_card_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_app_deleted(app, subscription_app_deleted_webhook):
+ # given
+ webhooks = [subscription_app_deleted_webhook]
+
+ id = app.id
+ app.delete()
+ app.id = id
+
+ event_type = WebhookEventAsyncType.APP_DELETED
+ app_id = graphene.Node.to_global_id("App", app.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, app, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_app(app, app_id)
+ 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_app_status_changed(status, app, subscription_app_status_changed_webhook):
+ # given
+ webhooks = [subscription_app_status_changed_webhook]
+
+ app.is_active = status
+ app.save(update_fields=["is_active"])
+
+ event_type = WebhookEventAsyncType.APP_STATUS_CHANGED
+ app_id = graphene.Node.to_global_id("App", app.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, app, webhooks)
+
+ # then
+ expected_payload = generate_expected_payload_for_app(app, app_id)
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_category_created(category, subscription_category_created_webhook):
# given
webhooks = [subscription_category_created_webhook]
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 3fc0f1440f..25a9d82e7d 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -1,5 +1,6 @@
from ..core.permissions import (
AccountPermissions,
+ AppPermission,
ChannelPermissions,
CheckoutPermissions,
DiscountPermissions,
@@ -17,6 +18,11 @@ from ..core.permissions import (
class WebhookEventAsyncType:
ANY = "any_events"
+ APP_CREATED = "app_created"
+ APP_UPDATED = "app_updated"
+ APP_DELETED = "app_deleted"
+ APP_STATUS_CHANGED = "app_status_changed"
+
CATEGORY_CREATED = "category_created"
CATEGORY_UPDATED = "category_updated"
CATEGORY_DELETED = "category_deleted"
@@ -106,6 +112,10 @@ class WebhookEventAsyncType:
DISPLAY_LABELS = {
ANY: "Any events",
+ APP_CREATED: "App created",
+ APP_UPDATED: "App updated",
+ APP_DELETED: "App deleted",
+ APP_STATUS_CHANGED: "App status changed",
CATEGORY_CREATED: "Category created",
CATEGORY_UPDATED: "Category updated",
CATEGORY_DELETED: "Category deleted",
@@ -175,6 +185,10 @@ class WebhookEventAsyncType:
CHOICES = [
(ANY, DISPLAY_LABELS[ANY]),
+ (APP_CREATED, DISPLAY_LABELS[APP_CREATED]),
+ (APP_UPDATED, DISPLAY_LABELS[APP_UPDATED]),
+ (APP_DELETED, DISPLAY_LABELS[APP_DELETED]),
+ (APP_STATUS_CHANGED, DISPLAY_LABELS[APP_STATUS_CHANGED]),
(CATEGORY_CREATED, DISPLAY_LABELS[CATEGORY_CREATED]),
(CATEGORY_UPDATED, DISPLAY_LABELS[CATEGORY_UPDATED]),
(CATEGORY_DELETED, DISPLAY_LABELS[CATEGORY_DELETED]),
@@ -245,6 +259,10 @@ class WebhookEventAsyncType:
ALL = [event[0] for event in CHOICES]
PERMISSIONS = {
+ APP_CREATED: AppPermission.MANAGE_APPS,
+ APP_UPDATED: AppPermission.MANAGE_APPS,
+ APP_DELETED: AppPermission.MANAGE_APPS,
+ APP_STATUS_CHANGED: AppPermission.MANAGE_APPS,
CATEGORY_CREATED: ProductPermissions.MANAGE_PRODUCTS,
CATEGORY_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
CATEGORY_DELETED: ProductPermissions.MANAGE_PRODUCTS,
@@ -385,6 +403,10 @@ class WebhookEventSyncType:
SUBSCRIBABLE_EVENTS = [
+ WebhookEventAsyncType.APP_CREATED,
+ WebhookEventAsyncType.APP_UPDATED,
+ WebhookEventAsyncType.APP_DELETED,
+ WebhookEventAsyncType.APP_STATUS_CHANGED,
WebhookEventAsyncType.CATEGORY_CREATED,
WebhookEventAsyncType.CATEGORY_UPDATED,
WebhookEventAsyncType.CATEGORY_DELETED,