Skip to content

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

Category webhook events added (#9490)

SzymJ6c3162f2c6d2
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 4a5d8a3cfc..77bdf686a7 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -145,6 +145,10 @@ class CategoryCreate(ModelMutation):
if cleaned_input.get("background_image"):
create_category_background_image_thumbnails.delay(instance.pk)
+ @classmethod
+ def post_save_action(cls, info, instance, _cleaned_input):
+ info.context.plugins.category_created(instance)
+
class CategoryUpdate(CategoryCreate):
class Arguments:
@@ -161,6 +165,10 @@ class CategoryUpdate(CategoryCreate):
error_type_class = ProductError
error_type_field = "product_errors"
+ @classmethod
+ def post_save_action(cls, info, instance, _cleaned_input):
+ info.context.plugins.category_updated(instance)
+
class CategoryDelete(ModelDeleteMutation):
class Arguments:
@@ -184,6 +192,7 @@ class CategoryDelete(ModelDeleteMutation):
delete_categories([db_id], manager=info.context.plugins)
instance.id = db_id
+ info.context.plugins.category_deleted(instance)
return cls.success_response(instance)
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index 3b2a2a87e3..3dcf6d8300 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -3,6 +3,7 @@ from unittest.mock import Mock, patch
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from graphql_relay import to_global_id
@@ -10,6 +11,7 @@ from ....product.error_codes import ProductErrorCode
from ....product.models import Category, Product, ProductChannelListing
from ....product.tests.utils import create_image, create_pdf_file_with_image_ext
from ....tests.utils import dummy_editorjs
+from ....webhook.event_types import WebhookEventAsyncType
from ...tests.utils import (
get_graphql_content,
get_graphql_content_from_response,
@@ -444,6 +446,66 @@ def test_category_create_mutation(
assert data["category"]["parent"]["id"] == parent_id
+@patch("saleor.plugins.webhook.plugin._get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_category_create_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ monkeypatch,
+ staff_api_client,
+ permission_manage_products,
+ media_root,
+ settings,
+):
+ query = CATEGORY_CREATE_MUTATION
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ mock_create_thumbnails = Mock(return_value=None)
+ monkeypatch.setattr(
+ (
+ "saleor.product.thumbnails."
+ "create_category_background_image_thumbnails.delay"
+ ),
+ mock_create_thumbnails,
+ )
+
+ category_name = "Test category"
+ description = "description"
+ category_slug = slugify(category_name)
+ category_description = dummy_editorjs(description, True)
+ image_file, image_name = create_image()
+ image_alt = "Alt text for an image."
+
+ # test creating root category
+ variables = {
+ "name": category_name,
+ "description": category_description,
+ "backgroundImage": image_name,
+ "backgroundImageAlt": image_alt,
+ "slug": category_slug,
+ }
+ body = get_multipart_request_body(query, variables, image_file, image_name)
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["categoryCreate"]
+ category = Category.objects.first()
+
+ assert category
+ assert data["errors"] == []
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": graphene.Node.to_global_id("Category", category.id)},
+ WebhookEventAsyncType.CATEGORY_CREATED,
+ [any_webhook],
+ category,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
@pytest.mark.parametrize(
"input_slug, expected_slug",
(
@@ -605,6 +667,65 @@ def test_category_update_mutation(
assert data["category"]["backgroundImage"]["alt"] == image_alt
+@patch("saleor.plugins.webhook.plugin._get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_category_update_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ monkeypatch,
+ staff_api_client,
+ category,
+ permission_manage_products,
+ media_root,
+ settings,
+):
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ mock_create_thumbnails = Mock(return_value=None)
+ monkeypatch.setattr(
+ (
+ "saleor.product.thumbnails."
+ "create_category_background_image_thumbnails.delay"
+ ),
+ mock_create_thumbnails,
+ )
+
+ category_name = "Updated name"
+ description = "description"
+ category_slug = slugify(category_name)
+ category_description = dummy_editorjs(description, True)
+
+ image_file, image_name = create_image()
+ image_alt = "Alt text for an image."
+
+ variables = {
+ "name": category_name,
+ "description": category_description,
+ "backgroundImage": image_name,
+ "backgroundImageAlt": image_alt,
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "slug": category_slug,
+ }
+ body = get_multipart_request_body(
+ MUTATION_CATEGORY_UPDATE_MUTATION, variables, image_file, image_name
+ )
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["categoryUpdate"]
+ assert data["errors"] == []
+
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": variables["id"]},
+ WebhookEventAsyncType.CATEGORY_UPDATED,
+ [any_webhook],
+ category,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
def test_category_update_mutation_invalid_background_image(
staff_api_client, category, permission_manage_products
):
@@ -867,6 +988,42 @@ def test_category_delete_mutation(
delete_versatile_image_mock.assert_not_called()
+@patch("saleor.product.signals.delete_versatile_image")
+@patch("saleor.plugins.webhook.plugin._get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_category_delete_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ delete_versatile_image_mock,
+ any_webhook,
+ staff_api_client,
+ category,
+ permission_manage_products,
+ settings,
+):
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ variables = {"id": graphene.Node.to_global_id("Category", category.id)}
+ response = staff_api_client.post_graphql(
+ MUTATION_CATEGORY_DELETE, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["categoryDelete"]
+ assert data["category"]["name"] == category.name
+
+ assert not Category.objects.first()
+
+ delete_versatile_image_mock.assert_not_called()
+ mocked_webhook_trigger.assert_called_once_with(
+ {"id": variables["id"]},
+ WebhookEventAsyncType.CATEGORY_DELETED,
+ [any_webhook],
+ category,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
@patch("saleor.product.signals.delete_versatile_image")
def test_delete_category_with_background_image(
delete_versatile_image_mock,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index fe5a005da1..c1710aa373 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1093,12 +1093,38 @@ type WebhookEvent {
"""Enum determining type of webhook."""
enum WebhookEventTypeEnum {
+ """All the events."""
ANY_EVENTS
+
+ """A new category created."""
+ CATEGORY_CREATED
+
+ """A category is updated."""
+ CATEGORY_UPDATED
+
+ """A category is deleted."""
+ CATEGORY_DELETED
+
+ """A new order is placed."""
ORDER_CREATED
+
+ """
+ An order is confirmed (status change unconfirmed -> unfulfilled) by a staff user using the OrderConfirm mutation. It also triggers when the user completes the checkout and the shop setting `automatically_confirm_all_new_orders` is enabled.
+ """
ORDER_CONFIRMED
+
+ """Payment is made and an order is fully paid."""
ORDER_FULLY_PAID
+
+ """
+ An order is updated; triggered for all changes related to an order; covers all other order webhooks, except for ORDER_CREATED.
+ """
ORDER_UPDATED
+
+ """An order is cancelled."""
ORDER_CANCELLED
+
+ """An order is fulfilled."""
ORDER_FULFILLED
DRAFT_ORDER_CREATED
DRAFT_ORDER_UPDATED
@@ -1106,29 +1132,75 @@ enum WebhookEventTypeEnum {
SALE_CREATED
SALE_UPDATED
SALE_DELETED
+
+ """An invoice for order requested."""
INVOICE_REQUESTED
+
+ """An invoice is deleted."""
INVOICE_DELETED
+
+ """Invoice has been sent."""
INVOICE_SENT
+
+ """A new customer account is created."""
CUSTOMER_CREATED
+
+ """A customer account is updated."""
CUSTOMER_UPDATED
+
+ """A new collection is created."""
COLLECTION_CREATED
+
+ """A collection is updated."""
COLLECTION_UPDATED
+
+ """A collection is deleted."""
COLLECTION_DELETED
+
+ """A new product is created."""
PRODUCT_CREATED
+
+ """A product is updated."""
PRODUCT_UPDATED
+
+ """A product is deleted."""
PRODUCT_DELETED
+
+ """A new product variant is created."""
PRODUCT_VARIANT_CREATED
+
+ """A product variant is updated."""
PRODUCT_VARIANT_UPDATED
+
+ """A product variant is deleted."""
PRODUCT_VARIANT_DELETED
PRODUCT_VARIANT_OUT_OF_STOCK
PRODUCT_VARIANT_BACK_IN_STOCK
+
+ """A new checkout is created."""
CHECKOUT_CREATED
+
+ """
+ A checkout is updated. It also triggers all updates related to the checkout.
+ """
CHECKOUT_UPDATED
+
+ """A new fulfillment is created."""
FULFILLMENT_CREATED
+
+ """A fulfillment is cancelled."""
FULFILLMENT_CANCELED
+
+ """User notification triggered."""
NOTIFY_USER
+
+ """A new page is created."""
PAGE_CREATED
+
+ """A page is updated."""
PAGE_UPDATED
+
+ """A page is deleted."""
PAGE_DELETED
TRANSLATION_CREATED
TRANSLATION_UPDATED
@@ -1181,6 +1253,15 @@ enum WebhookEventTypeAsyncEnum {
"""All the events."""
ANY_EVENTS
+ """A new category created."""
+ CATEGORY_CREATED
+
+ """A category is updated."""
+ CATEGORY_UPDATED
+
+ """A category is deleted."""
+ CATEGORY_DELETED
+
"""A new order is placed."""
ORDER_CREATED
@@ -1640,6 +1721,9 @@ scalar JSONString
"""An enumeration."""
enum WebhookSampleEventTypeEnum {
+ CATEGORY_CREATED
+ CATEGORY_UPDATED
+ CATEGORY_DELETED
ORDER_CREATED
ORDER_CONFIRMED
ORDER_FULLY_PAID
@@ -16461,7 +16545,28 @@ type Subscription {
event: Event
}
-union Event = 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 | TranslationCreated | TranslationUpdated
+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 | TranslationCreated | TranslationUpdated
+
+type CategoryCreated {
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
+
+type CategoryUpdated {
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
+
+type CategoryDeleted {
+ """
+ New in Saleor 3.2. Look up a category. Note: this feature is in a preview state and can be subject to changes at later point.
+ """
+ category: Category
+}
type OrderCreated {
"""
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index f31c44f85d..4bfad16d4e 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -3,80 +3,65 @@ import graphene
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..core.utils import str_to_enum
+checkout_updated_event_enum_description = (
+ "A checkout is updated. It also triggers all updates related to the checkout."
+)
+
+order_confirmed_event_enum_description = (
+ "An order is confirmed (status change unconfirmed -> unfulfilled) "
+ "by a staff user using the OrderConfirm mutation. "
+ "It also triggers when the user completes the checkout and the shop "
+ "setting `automatically_confirm_all_new_orders` is enabled."
+)
+
+order_fully_paid_event_enum_description = "Payment is made and an order is fully paid."
+
+order_updated_event_enum_description = (
+ "An order is updated; triggered for all changes related to an order; "
+ "covers all other order webhooks, except for ORDER_CREATED."
+)
+
+
+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.CHECKOUT_CREATED: "A new checkout is created.",
+ WebhookEventAsyncType.CHECKOUT_UPDATED: checkout_updated_event_enum_description,
+ WebhookEventAsyncType.COLLECTION_CREATED: "A new collection is created.",
+ WebhookEventAsyncType.COLLECTION_UPDATED: "A collection is updated.",
+ WebhookEventAsyncType.COLLECTION_DELETED: "A collection is deleted.",
+ WebhookEventAsyncType.CUSTOMER_CREATED: "A new customer account is created.",
+ WebhookEventAsyncType.CUSTOMER_UPDATED: "A customer account is updated.",
+ WebhookEventAsyncType.NOTIFY_USER: "User notification triggered.",
+ WebhookEventAsyncType.ORDER_CREATED: "A new order is placed.",
+ WebhookEventAsyncType.ORDER_CONFIRMED: order_confirmed_event_enum_description,
+ WebhookEventAsyncType.ORDER_FULLY_PAID: order_fully_paid_event_enum_description,
+ WebhookEventAsyncType.ORDER_UPDATED: order_updated_event_enum_description,
+ WebhookEventAsyncType.ORDER_CANCELLED: "An order is cancelled.",
+ WebhookEventAsyncType.ORDER_FULFILLED: "An order is fulfilled.",
+ WebhookEventAsyncType.FULFILLMENT_CREATED: "A new fulfillment is created.",
+ WebhookEventAsyncType.FULFILLMENT_CANCELED: "A fulfillment is cancelled.",
+ WebhookEventAsyncType.PAGE_CREATED: "A new page is created.",
+ WebhookEventAsyncType.PAGE_UPDATED: "A page is updated.",
+ WebhookEventAsyncType.PAGE_DELETED: "A page is deleted.",
+ WebhookEventAsyncType.PRODUCT_CREATED: "A new product is created.",
+ WebhookEventAsyncType.PRODUCT_UPDATED: "A product is updated.",
+ WebhookEventAsyncType.PRODUCT_DELETED: "A product is deleted.",
+ WebhookEventAsyncType.PRODUCT_VARIANT_CREATED: "A new product variant is created.",
+ WebhookEventAsyncType.PRODUCT_VARIANT_UPDATED: "A product variant is updated.",
+ WebhookEventAsyncType.PRODUCT_VARIANT_DELETED: "A product variant is deleted.",
+ WebhookEventAsyncType.INVOICE_REQUESTED: "An invoice for order requested.",
+ WebhookEventAsyncType.INVOICE_DELETED: "An invoice is deleted.",
+ WebhookEventAsyncType.INVOICE_SENT: "Invoice has been sent.",
+ WebhookEventAsyncType.ANY: "All the events.",
+}
+
def description(enum):
- if enum is None:
- return "Enum determining type of webhook."
- elif enum == WebhookEventTypeAsyncEnum.CHECKOUT_CREATED:
- return "A new checkout is created."
- elif enum == WebhookEventTypeAsyncEnum.CHECKOUT_UPDATED:
- return (
- "A checkout is updated. "
- "It also triggers all updates related to the checkout."
- )
- elif enum == WebhookEventTypeAsyncEnum.COLLECTION_CREATED:
- return "A new collection is created."
- elif enum == WebhookEventTypeAsyncEnum.COLLECTION_UPDATED:
- return "A collection is updated."
- elif enum == WebhookEventTypeAsyncEnum.COLLECTION_DELETED:
- return "A collection is deleted."
- elif enum == WebhookEventTypeAsyncEnum.CUSTOMER_CREATED:
- return "A new customer account is created."
- elif enum == WebhookEventTypeAsyncEnum.CUSTOMER_UPDATED:
- return "A customer account is updated."
- elif enum == WebhookEventTypeAsyncEnum.NOTIFY_USER:
- return "User notification triggered."
- elif enum == WebhookEventTypeAsyncEnum.ORDER_CREATED:
- return "A new order is placed."
- elif enum == WebhookEventTypeAsyncEnum.ORDER_CONFIRMED:
- return (
- "An order is confirmed (status change unconfirmed -> unfulfilled) "
- "by a staff user using the OrderConfirm mutation. "
- "It also triggers when the user completes the checkout and the shop "
- "setting `automatically_confirm_all_new_orders` is enabled."
- )
- elif enum == WebhookEventTypeAsyncEnum.ORDER_FULLY_PAID:
- return "Payment is made and an order is fully paid."
- elif enum == WebhookEventTypeAsyncEnum.ORDER_UPDATED:
- return (
- "An order is updated; triggered for all changes related to an order; "
- "covers all other order webhooks, except for ORDER_CREATED."
- )
- elif enum == WebhookEventTypeAsyncEnum.ORDER_CANCELLED:
- return "An order is cancelled."
- elif enum == WebhookEventTypeAsyncEnum.ORDER_FULFILLED:
- return "An order is fulfilled."
- elif enum == WebhookEventTypeAsyncEnum.FULFILLMENT_CREATED:
- return "A new fulfillment is created."
- elif enum == WebhookEventTypeAsyncEnum.FULFILLMENT_CANCELED:
- return "A fulfillment is cancelled."
- elif enum == WebhookEventTypeAsyncEnum.PAGE_CREATED:
- return "A new page is created."
- elif enum == WebhookEventTypeAsyncEnum.PAGE_UPDATED:
- return "A page is updated."
- elif enum == WebhookEventTypeAsyncEnum.PAGE_DELETED:
- return "A page is deleted."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_CREATED:
- return "A new product is created."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_UPDATED:
- return "A product is updated."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_DELETED:
- return "A product is deleted."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_VARIANT_CREATED:
- return "A new product variant is created."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_VARIANT_UPDATED:
- return "A product variant is updated."
- elif enum == WebhookEventTypeAsyncEnum.PRODUCT_VARIANT_DELETED:
- return "A product variant is deleted."
- elif enum == WebhookEventTypeAsyncEnum.INVOICE_REQUESTED:
- return "An invoice for order requested."
- elif enum == WebhookEventTypeAsyncEnum.INVOICE_DELETED:
- return "An invoice is deleted."
- elif enum == WebhookEventTypeAsyncEnum.INVOICE_SENT:
- return "Invoice has been sent."
- elif enum == WebhookEventTypeAsyncEnum.ANY_EVENTS:
- return "All the events."
- return None
+ if enum:
+ return WEBHOOK_EVENT_DESCRIPTION.get(enum.value)
+ return "Enum determining type of webhook."
WebhookEventTypeEnum = graphene.Enum(
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 565ba51570..8ff2cfdd12 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -33,6 +33,30 @@ TRANSLATIONS_TYPES_MAP = {
}
+class CategoryBase(AbstractType):
+ category = graphene.Field(
+ "saleor.graphql.product.types.Category",
+ description=f"{ADDED_IN_32} Look up a category. {PREVIEW_FEATURE}",
+ )
+
+ @staticmethod
+ def resolve_category(root, info):
+ _, category = root
+ return category
+
+
+class CategoryCreated(ObjectType, CategoryBase):
+ ...
+
+
+class CategoryUpdated(ObjectType, CategoryBase):
+ ...
+
+
+class CategoryDeleted(ObjectType, CategoryBase):
+ ...
+
+
class OrderBase(AbstractType):
order = graphene.Field(
"saleor.graphql.order.types.Order",
@@ -378,6 +402,9 @@ class TranslationUpdated(ObjectType, TranslationBase):
class Event(Union):
class Meta:
types = (
+ CategoryCreated,
+ CategoryUpdated,
+ CategoryDeleted,
OrderCreated,
OrderUpdated,
OrderConfirmed,
@@ -420,6 +447,9 @@ class Event(Union):
@classmethod
def get_type(cls, object_type: str):
types = {
+ WebhookEventAsyncType.CATEGORY_CREATED: CategoryCreated,
+ WebhookEventAsyncType.CATEGORY_UPDATED: CategoryUpdated,
+ WebhookEventAsyncType.CATEGORY_DELETED: CategoryDeleted,
WebhookEventAsyncType.ORDER_CREATED: OrderCreated,
WebhookEventAsyncType.ORDER_UPDATED: OrderUpdated,
WebhookEventAsyncType.ORDER_CONFIRMED: OrderConfirmed,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 1850c4fafb..1d68963629 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -39,7 +39,13 @@ if TYPE_CHECKING:
from ..invoice.models import Invoice
from ..order.models import Fulfillment, Order, OrderLine
from ..page.models import Page
- from ..product.models import Collection, Product, ProductType, ProductVariant
+ from ..product.models import (
+ Category,
+ Collection,
+ Product,
+ ProductType,
+ ProductVariant,
+ )
from ..shipping.interface import ShippingMethodData
PluginConfigurationType = List[dict]
@@ -228,6 +234,24 @@ class BasePlugin:
capture_payment: Callable[["PaymentData", Any], GatewayResponse]
+ # Trigger when category is created.
+ #
+ # Overwrite this method if you need to trigger specific logic after a category is
+ # created.
+ category_created: Callable[["Category", None], None]
+
+ # Trigger when category is deleted.
+ #
+ # Overwrite this method if you need to trigger specific logic after a category is
+ # deleted.
+ category_deleted: Callable[["Category", None], None]
+
+ # Trigger when category is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a category is
+ # updated.
+ category_updated: Callable[["Category", 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.py
index f0c29ca7c8..92edf35050 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -54,7 +54,13 @@ if TYPE_CHECKING:
PaymentGateway,
TokenConfig,
)
- from ..product.models import Collection, Product, ProductType, ProductVariant
+ from ..product.models import (
+ Category,
+ Collection,
+ Product,
+ ProductType,
+ ProductVariant,
+ )
from ..shipping.interface import ShippingMethodData
from ..translation.models import Translation
from ..warehouse.models import Stock
@@ -780,6 +786,18 @@ class PluginsManager(PaymentInterface):
default_value = None
return self.__run_method_on_plugins("page_deleted", default_value, page)
+ def category_created(self, category: "Category"):
+ default_value = None
+ return self.__run_method_on_plugins("category_created", default_value, category)
+
+ def category_updated(self, category: "Category"):
+ default_value = None
+ return self.__run_method_on_plugins("category_updated", default_value, category)
+
+ def category_deleted(self, category: "Category"):
+ default_value = None
+ return self.__run_method_on_plugins("category_deleted", default_value, category)
+
def initialize_payment(
self, gateway, payment_data: dict, channel_slug: str
) -> Optional["InitializedPaymentResponse"]:
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 8aea9bb880..61f338f3a9 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -2,6 +2,8 @@ import json
import logging
from typing import TYPE_CHECKING, Any, List, Optional, Union
+import graphene
+
from ...app.models import App
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
@@ -55,7 +57,7 @@ if TYPE_CHECKING:
from ...order.models import Fulfillment, Order
from ...page.models import Page
from ...payment.interface import GatewayResponse, PaymentData, PaymentGateway
- from ...product.models import Collection, Product, ProductVariant
+ from ...product.models import Category, Collection, Product, ProductVariant
from ...shipping.interface import ShippingMethodData
from ...translation.models import Translation
from ...warehouse.models import Stock
@@ -81,6 +83,36 @@ class WebhookPlugin(BasePlugin):
super().__init__(*args, **kwargs)
self.active = True
+ def category_created(self, category: "Category", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.CATEGORY_CREATED
+ if webhooks := _get_webhooks_for_event(event_type):
+ payload = {"id": graphene.Node.to_global_id("Category", category.id)}
+ trigger_webhooks_async(
+ payload, event_type, webhooks, category, self.requestor
+ )
+
+ def category_updated(self, category: "Category", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.CATEGORY_UPDATED
+ if webhooks := _get_webhooks_for_event(event_type):
+ payload = {"id": graphene.Node.to_global_id("Category", category.id)}
+ trigger_webhooks_async(
+ payload, event_type, webhooks, category, self.requestor
+ )
+
+ def category_deleted(self, category: "Category", previous_value: None) -> None:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.CATEGORY_DELETED
+ if webhooks := _get_webhooks_for_event(event_type):
+ payload = {"id": graphene.Node.to_global_id("Category", category.id)}
+ trigger_webhooks_async(
+ payload, event_type, webhooks, category, self.requestor
+ )
+
def order_created(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 600f27d345..75579cf8c1 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -19,6 +19,66 @@ def subscription_webhook(app):
return fun
+CATEGORY_CREATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CategoryCreated{
+ category{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_category_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ CATEGORY_CREATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CATEGORY_CREATED
+ )
+
+
+CATEGORY_UPDATED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CategoryUpdated{
+ category{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_category_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ CATEGORY_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CATEGORY_UPDATED
+ )
+
+
+CATEGORY_DELETED_SUBSCRIPTION_QUERY = """
+ subscription{
+ event{
+ ...on CategoryDeleted{
+ category{
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def subscription_category_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ CATEGORY_DELETED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.CATEGORY_DELETED
+ )
+
+
PRODUCT_UPDATED_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 d3eefeda23..c65c3478d8 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
@@ -8,6 +8,54 @@ from .....webhook.event_types import WebhookEventAsyncType
from ...tasks import create_deliveries_for_subscriptions, logger
+def test_category_created(category, subscription_category_created_webhook):
+ # given
+ webhooks = [subscription_category_created_webhook]
+ event_type = WebhookEventAsyncType.CATEGORY_CREATED
+ category_id = graphene.Node.to_global_id("Category", category.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, category, webhooks)
+
+ # then
+ expected_payload = json.dumps([{"category": {"id": category_id}, "meta": None}])
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_category_updated(category, subscription_category_updated_webhook):
+ # given
+ webhooks = [subscription_category_updated_webhook]
+ event_type = WebhookEventAsyncType.CATEGORY_UPDATED
+ category_id = graphene.Node.to_global_id("Category", category.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, category, webhooks)
+
+ # then
+ expected_payload = json.dumps([{"category": {"id": category_id}, "meta": None}])
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_category_deleted(category, subscription_category_deleted_webhook):
+ # given
+ webhooks = [subscription_category_deleted_webhook]
+ event_type = WebhookEventAsyncType.CATEGORY_DELETED
+ category_id = graphene.Node.to_global_id("Category", category.id)
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, category, webhooks)
+
+ # then
+ expected_payload = json.dumps([{"category": {"id": category_id}, "meta": None}])
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_product_created(product, subscription_product_created_webhook):
webhooks = [subscription_product_created_webhook]
event_type = WebhookEventAsyncType.PRODUCT_CREATED
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index ab984f044e..2842854a77 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -13,6 +13,11 @@ from ..core.permissions import (
class WebhookEventAsyncType:
ANY = "any_events"
+
+ CATEGORY_CREATED = "category_created"
+ CATEGORY_UPDATED = "category_updated"
+ CATEGORY_DELETED = "category_deleted"
+
ORDER_CREATED = "order_created"
ORDER_CONFIRMED = "order_confirmed"
ORDER_FULLY_PAID = "order_fully_paid"
@@ -67,6 +72,9 @@ class WebhookEventAsyncType:
DISPLAY_LABELS = {
ANY: "Any events",
+ CATEGORY_CREATED: "Category created",
+ CATEGORY_UPDATED: "Category updated",
+ CATEGORY_DELETED: "Category deleted",
ORDER_CREATED: "Order created",
ORDER_CONFIRMED: "Order confirmed",
ORDER_FULLY_PAID: "Order paid",
@@ -109,6 +117,9 @@ class WebhookEventAsyncType:
CHOICES = [
(ANY, DISPLAY_LABELS[ANY]),
+ (CATEGORY_CREATED, DISPLAY_LABELS[CATEGORY_CREATED]),
+ (CATEGORY_UPDATED, DISPLAY_LABELS[CATEGORY_UPDATED]),
+ (CATEGORY_DELETED, DISPLAY_LABELS[CATEGORY_DELETED]),
(ORDER_CREATED, DISPLAY_LABELS[ORDER_CREATED]),
(ORDER_CONFIRMED, DISPLAY_LABELS[ORDER_CONFIRMED]),
(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),
@@ -152,6 +163,9 @@ class WebhookEventAsyncType:
ALL = [event[0] for event in CHOICES]
PERMISSIONS = {
+ CATEGORY_CREATED: ProductPermissions.MANAGE_PRODUCTS,
+ CATEGORY_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
+ CATEGORY_DELETED: ProductPermissions.MANAGE_PRODUCTS,
ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,
ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,
@@ -265,6 +279,9 @@ class WebhookEventSyncType:
SUBSCRIBABLE_EVENTS = [
+ WebhookEventAsyncType.CATEGORY_CREATED,
+ WebhookEventAsyncType.CATEGORY_UPDATED,
+ WebhookEventAsyncType.CATEGORY_DELETED,
WebhookEventAsyncType.ORDER_CREATED,
WebhookEventAsyncType.ORDER_UPDATED,
WebhookEventAsyncType.ORDER_CONFIRMED,