Skip to content

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

Add webhooks for collections create/update/delete (#8974)

Rafał Pitoń3f8a1afe77ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e15e90d7ea..e3a6cf6359 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.
- in update mutations: do not require providing any attributes; when any attribute is given, validate provided values.
- Do no allow using id for updating checkout and order metadata - #8906 by @IKarbowiak
- Fix crash when querying external shipping method's `translation` field - #8971 by @rafalp
+- Add `COLLECTION_CREATED`, `COLLECTION_UPDATED`, `COLLECTION_DELETED` events and webhooks - #8974 by @rafalp
# 3.0.0 [Unreleased]
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index a41fefda6f..a4bd3c9212 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -249,6 +249,8 @@ class CollectionCreate(ModelMutation):
@classmethod
def post_save_action(cls, info, instance, cleaned_input):
+ info.context.plugins.collection_created(instance)
+
products = instance.products.prefetched_for_webhook(single_object=False)
for product in products:
info.context.plugins.product_updated(product)
@@ -278,7 +280,7 @@ class CollectionUpdate(CollectionCreate):
@classmethod
def post_save_action(cls, info, instance, cleaned_input):
"""Override this method with `pass` to avoid triggering product webhook."""
- pass
+ info.context.plugins.collection_updated(instance)
@classmethod
def save(cls, info, instance, cleaned_input):
@@ -306,8 +308,11 @@ class CollectionDelete(ModelDeleteMutation):
products = list(instance.products.prefetched_for_webhook(single_object=False))
result = super().perform_mutation(_root, info, **kwargs)
+
+ info.context.plugins.collection_deleted(instance)
for product in products:
info.context.plugins.product_updated(product)
+
return CollectionDelete(
collection=ChannelContext(node=result.collection, channel_slug=None)
)
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index d5b742e793..ea4b2e04cd 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -459,8 +459,16 @@ CREATE_COLLECTION_MUTATION = """
"""
+@patch("saleor.plugins.manager.PluginsManager.collection_updated")
+@patch("saleor.plugins.manager.PluginsManager.collection_created")
def test_create_collection(
- monkeypatch, staff_api_client, product_list, media_root, permission_manage_products
+ created_webhook_mock,
+ updated_webhook_mock,
+ monkeypatch,
+ staff_api_client,
+ product_list,
+ media_root,
+ permission_manage_products,
):
query = CREATE_COLLECTION_MUTATION
@@ -507,6 +515,9 @@ def test_create_collection(
mock_create_thumbnails.assert_called_once_with(collection.pk)
assert data["backgroundImage"]["alt"] == image_alt
+ created_webhook_mock.assert_called_once()
+ updated_webhook_mock.assert_not_called()
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_create_collection_trigger_product_update_webhook(
@@ -604,8 +615,15 @@ def test_create_collection_name_with_unicode(
assert data["collection"]["slug"] == "わたし-わ-にっぽん-です"
+@patch("saleor.plugins.manager.PluginsManager.collection_updated")
+@patch("saleor.plugins.manager.PluginsManager.collection_created")
def test_update_collection(
- monkeypatch, staff_api_client, collection, permission_manage_products
+ created_webhook_mock,
+ updated_webhook_mock,
+ monkeypatch,
+ staff_api_client,
+ collection,
+ permission_manage_products,
):
query = """
mutation updateCollection(
@@ -650,6 +668,9 @@ def test_update_collection(
assert data["slug"] == slug
assert mock_create_thumbnails.call_count == 0
+ created_webhook_mock.assert_not_called()
+ updated_webhook_mock.assert_called_once()
+
MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE = """
mutation updateCollection($name: String!, $slug: String!, $id: ID!,
@@ -908,9 +929,11 @@ DELETE_COLLECTION_MUTATION = """
"""
+@patch("saleor.plugins.manager.PluginsManager.collection_deleted")
@patch("saleor.product.signals.delete_versatile_image")
def test_delete_collection(
delete_versatile_image_mock,
+ deleted_webhook_mock,
staff_api_client,
collection,
permission_manage_products,
@@ -928,6 +951,8 @@ def test_delete_collection(
collection.refresh_from_db()
delete_versatile_image_mock.assert_not_called()
+ deleted_webhook_mock.assert_called_once()
+
@patch("saleor.product.signals.delete_versatile_image")
def test_delete_collection_with_background_image(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 218aa14a95..221c22489c 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -7418,6 +7418,9 @@ enum WebhookEventTypeAsyncEnum {
INVOICE_SENT
CUSTOMER_CREATED
CUSTOMER_UPDATED
+ COLLECTION_CREATED
+ COLLECTION_UPDATED
+ COLLECTION_DELETED
PRODUCT_CREATED
PRODUCT_UPDATED
PRODUCT_DELETED
@@ -7457,6 +7460,9 @@ enum WebhookEventTypeEnum {
INVOICE_SENT
CUSTOMER_CREATED
CUSTOMER_UPDATED
+ COLLECTION_CREATED
+ COLLECTION_UPDATED
+ COLLECTION_DELETED
PRODUCT_CREATED
PRODUCT_UPDATED
PRODUCT_DELETED
@@ -7514,6 +7520,9 @@ enum WebhookSampleEventTypeEnum {
INVOICE_SENT
CUSTOMER_CREATED
CUSTOMER_UPDATED
+ COLLECTION_CREATED
+ COLLECTION_UPDATED
+ COLLECTION_DELETED
PRODUCT_CREATED
PRODUCT_UPDATED
PRODUCT_DELETED
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 7a069756b9..f31c44f85d 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -14,6 +14,12 @@ def description(enum):
"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:
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index f19e6e2909..f4992b7b01 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -36,7 +36,7 @@ if TYPE_CHECKING:
from ..invoice.models import Invoice
from ..order.models import Fulfillment, Order, OrderLine
from ..page.models import Page
- from ..product.models import Product, ProductType, ProductVariant
+ from ..product.models import Collection, Product, ProductType, ProductVariant
from ..shipping.interface import ShippingMethodData
PluginConfigurationType = List[dict]
@@ -241,6 +241,24 @@ class BasePlugin:
# updated.
checkout_updated: Callable[["Checkout", Any], Any]
+ # Trigger when collection is created.
+ #
+ # Overwrite this method if you need to trigger specific logic after a collection is
+ # created.
+ collection_created: Callable[["Collection", Any], Any]
+
+ # Trigger when collection is deleted.
+ #
+ # Overwrite this method if you need to trigger specific logic after a collection is
+ # deleted.
+ collection_deleted: Callable[["Collection", Any], Any]
+
+ # Trigger when collection is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a collection is
+ # updated.
+ collection_updated: Callable[["Collection", Any], Any]
+
confirm_payment: Callable[["PaymentData", Any], GatewayResponse]
# Trigger when user is created.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 0a8a25a532..b13043f6b9 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -51,7 +51,7 @@ if TYPE_CHECKING:
PaymentGateway,
TokenConfig,
)
- from ..product.models import Product, ProductType, ProductVariant
+ from ..product.models import Collection, Product, ProductType, ProductVariant
from ..shipping.interface import ShippingMethodData
from ..translation.models import Translation
from ..warehouse.models import Stock
@@ -545,6 +545,24 @@ class PluginsManager(PaymentInterface):
default_value = None
return self.__run_method_on_plugins("customer_updated", default_value, customer)
+ def collection_created(self, collection: "Collection"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "collection_created", default_value, collection
+ )
+
+ def collection_updated(self, collection: "Collection"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "collection_updated", default_value, collection
+ )
+
+ def collection_deleted(self, collection: "Collection"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "collection_deleted", default_value, collection
+ )
+
def product_created(self, product: "Product"):
default_value = None
return self.__run_method_on_plugins("product_created", default_value, product)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index ebde8e628a..654386bdb3 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -11,6 +11,7 @@ from ...payment import PaymentError, TransactionKind
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.payloads import (
generate_checkout_payload,
+ generate_collection_payload,
generate_customer_payload,
generate_fulfillment_payload,
generate_invoice_payload,
@@ -51,7 +52,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 Product, ProductVariant
+ from ...product.models import Collection, Product, ProductVariant
from ...shipping.interface import ShippingMethodData
from ...translation.models import Translation
from ...warehouse.models import Stock
@@ -221,6 +222,30 @@ class WebhookPlugin(BasePlugin):
customer_data = generate_customer_payload(customer, self.requestor)
trigger_webhooks_async(customer_data, WebhookEventAsyncType.CUSTOMER_UPDATED)
+ def collection_created(self, collection: "Collection", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ collection_data = generate_collection_payload(collection, self.requestor)
+ trigger_webhooks_async(
+ collection_data, WebhookEventAsyncType.COLLECTION_CREATED
+ )
+
+ def collection_updated(self, collection: "Collection", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ collection_data = generate_collection_payload(collection, self.requestor)
+ trigger_webhooks_async(
+ collection_data, WebhookEventAsyncType.COLLECTION_UPDATED
+ )
+
+ def collection_deleted(self, collection: "Collection", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ collection_data = generate_collection_payload(collection, self.requestor)
+ trigger_webhooks_async(
+ collection_data, WebhookEventAsyncType.COLLECTION_DELETED
+ )
+
def product_created(self, product: "Product", previous_value: Any) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index a0d16b15bc..0f15b231b5 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -29,6 +29,7 @@ from ....graphql.discount.mutations import convert_catalogue_info_to_global_ids
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.payloads import (
generate_checkout_payload,
+ generate_collection_payload,
generate_customer_payload,
generate_invoice_payload,
generate_order_payload,
@@ -214,6 +215,45 @@ def test_order_fully_paid(mocked_webhook_trigger, settings, order_with_lines):
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_collection_created(mocked_webhook_trigger, settings, collection):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ manager.collection_created(collection)
+ expected_data = generate_collection_payload(collection)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data, WebhookEventAsyncType.COLLECTION_CREATED
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_collection_updated(mocked_webhook_trigger, settings, collection):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ manager.collection_updated(collection)
+ expected_data = generate_collection_payload(collection)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data, WebhookEventAsyncType.COLLECTION_UPDATED
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_collection_deleted(mocked_webhook_trigger, settings, collection):
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ manager.collection_deleted(collection)
+ expected_data = generate_collection_payload(collection)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data, WebhookEventAsyncType.COLLECTION_DELETED
+ )
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
def test_product_created(mocked_webhook_trigger, settings, product):
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index ae3fb6be62..49fd665c3b 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -38,6 +38,10 @@ class WebhookEventAsyncType:
CUSTOMER_CREATED = "customer_created"
CUSTOMER_UPDATED = "customer_updated"
+ COLLECTION_CREATED = "collection_created"
+ COLLECTION_UPDATED = "collection_updated"
+ COLLECTION_DELETED = "collection_deleted"
+
PRODUCT_CREATED = "product_created"
PRODUCT_UPDATED = "product_updated"
PRODUCT_DELETED = "product_deleted"
@@ -80,6 +84,9 @@ class WebhookEventAsyncType:
INVOICE_SENT: "Invoice sent",
CUSTOMER_CREATED: "Customer created",
CUSTOMER_UPDATED: "Customer updated",
+ COLLECTION_CREATED: "Collection created",
+ COLLECTION_UPDATED: "Collection updated",
+ COLLECTION_DELETED: "Collection deleted",
PRODUCT_CREATED: "Product created",
PRODUCT_UPDATED: "Product updated",
PRODUCT_DELETED: "Product deleted",
@@ -119,6 +126,9 @@ class WebhookEventAsyncType:
(INVOICE_SENT, DISPLAY_LABELS[INVOICE_SENT]),
(CUSTOMER_CREATED, DISPLAY_LABELS[CUSTOMER_CREATED]),
(CUSTOMER_UPDATED, DISPLAY_LABELS[CUSTOMER_UPDATED]),
+ (COLLECTION_CREATED, DISPLAY_LABELS[COLLECTION_CREATED]),
+ (COLLECTION_UPDATED, DISPLAY_LABELS[COLLECTION_UPDATED]),
+ (COLLECTION_DELETED, DISPLAY_LABELS[COLLECTION_DELETED]),
(PRODUCT_CREATED, DISPLAY_LABELS[PRODUCT_CREATED]),
(PRODUCT_UPDATED, DISPLAY_LABELS[PRODUCT_UPDATED]),
(PRODUCT_DELETED, DISPLAY_LABELS[PRODUCT_DELETED]),
@@ -159,6 +169,9 @@ class WebhookEventAsyncType:
INVOICE_SENT: OrderPermissions.MANAGE_ORDERS,
CUSTOMER_CREATED: AccountPermissions.MANAGE_USERS,
CUSTOMER_UPDATED: AccountPermissions.MANAGE_USERS,
+ COLLECTION_CREATED: ProductPermissions.MANAGE_PRODUCTS,
+ COLLECTION_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
+ COLLECTION_DELETED: ProductPermissions.MANAGE_PRODUCTS,
PRODUCT_CREATED: ProductPermissions.MANAGE_PRODUCTS,
PRODUCT_UPDATED: ProductPermissions.MANAGE_PRODUCTS,
PRODUCT_DELETED: ProductPermissions.MANAGE_PRODUCTS,
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 422489138a..3056085aa8 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -28,7 +28,7 @@ from ..page.models import Page
from ..payment import ChargeStatus
from ..plugins.webhook.utils import from_payment_app_id
from ..product import ProductMediaTypes
-from ..product.models import Product
+from ..product.models import Collection, Product
from ..warehouse.models import Stock, Warehouse
from . import traced_payload_generator
from .event_types import WebhookEventAsyncType
@@ -486,6 +486,30 @@ def generate_customer_payload(
return data
+@traced_payload_generator
+def generate_collection_payload(
+ collection: "Collection", requestor: Optional["RequestorOrLazyObject"] = None
+):
+ serializer = PayloadSerializer()
+ data = serializer.serialize(
+ [collection],
+ fields=[
+ "name",
+ "description",
+ "background_image_alt",
+ "private_metadata",
+ "metadata",
+ ],
+ extra_dict_data={
+ "background_image": build_absolute_uri(collection.background_image.url)
+ if collection.background_image
+ else None,
+ "meta": generate_meta(requestor_data=generate_requestor(requestor)),
+ },
+ )
+ return data
+
+
PRODUCT_FIELDS = (
"name",
"description",
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 0bf128e8a6..d2aca8339c 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -26,6 +26,7 @@ from ..payloads import (
ORDER_FIELDS,
PRODUCT_VARIANT_FIELDS,
generate_checkout_payload,
+ generate_collection_payload,
generate_customer_payload,
generate_fulfillment_lines_payload,
generate_invoice_payload,
@@ -304,6 +305,29 @@ def test_order_line_without_sku_still_has_id(order, order_line_with_one_allocati
assert line_payload["product_variant_id"] == line.product_variant_id
+def test_generate_collection_payload(collection):
+ payload = json.loads(generate_collection_payload(collection))
+ expected_payload = [
+ {
+ "type": "Collection",
+ "id": graphene.Node.to_global_id("Collection", collection.id),
+ "name": collection.name,
+ "description": collection.description,
+ "background_image": None,
+ "background_image_alt": "",
+ "private_metadata": {},
+ "metadata": {},
+ "meta": {
+ "issued_at": ANY,
+ "version": __version__,
+ "issuing_principal": {"id": None, "type": None},
+ },
+ }
+ ]
+
+ assert payload == expected_payload
+
+
def test_generate_base_product_variant_payload(product_with_two_variants):
stocks_to_serialize = [
variant.stocks.first() for variant in product_with_two_variants.variants.all()