Skip to content

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

Add product type created/updated/deleted webhooks (#19351)

ayesha warisf261c2ef8db2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff1ed82b12..6bc87b3ec0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,8 @@ All notable, unreleased changes to this project will be documented in this file.
### Webhooks
+- Added `PRODUCT_TYPE_CREATED`, `PRODUCT_TYPE_UPDATED`, and `PRODUCT_TYPE_DELETED` webhook events, dispatched when a product type is created, updated, or deleted - #17574 by @ayesha-waris
+
### Other changes
#### Search improvements
diff --git a/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py
index 86fb146198..8584c9c09d 100644
--- a/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py
@@ -9,9 +9,12 @@ from ....attribute import models as attribute_models
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductTypePermissions
from ....product import models
+from ....webhook.event_types import WebhookEventAsyncType
+from ....webhook.utils import get_webhooks_for_event
from ...core import ResolveInfo
from ...core.mutations import ModelBulkDeleteMutation
from ...core.types import NonNullList, ProductError
+from ...plugins.dataloaders import get_plugin_manager_promise
from ..types import ProductType
@@ -49,6 +52,17 @@ class ProductTypeBulkDelete(ModelBulkDeleteMutation):
cls.delete_assigned_attribute_values(pks)
return super().perform_mutation(_root, info, ids=ids)
+ @classmethod
+ def bulk_action(cls, info: ResolveInfo, queryset, /):
+ product_types = list(queryset)
+ queryset.delete()
+ manager = get_plugin_manager_promise(info.context).get()
+ webhooks = get_webhooks_for_event(WebhookEventAsyncType.PRODUCT_TYPE_DELETED)
+ for product_type in product_types:
+ cls.call_event(
+ manager.product_type_deleted, product_type, webhooks=webhooks
+ )
+
@staticmethod
def delete_assigned_attribute_values(instance_pks):
attributes = attribute_models.Attribute.objects.filter(
diff --git a/saleor/graphql/product/mutations/product_type/product_type_create.py b/saleor/graphql/product/mutations/product_type/product_type_create.py
index 4451572232..70d452aed6 100644
--- a/saleor/graphql/product/mutations/product_type/product_type_create.py
+++ b/saleor/graphql/product/mutations/product_type/product_type_create.py
@@ -12,6 +12,7 @@ from ....core.mutations import DeprecatedModelMutation
from ....core.scalars import WeightScalar
from ....core.types import BaseInputObjectType, NonNullList, ProductError
from ....core.validators import validate_slug_and_generate_if_needed
+from ....plugins.dataloaders import get_plugin_manager_promise
from ...enums import ProductTypeKindEnum
from ...types import ProductType
from ..utils import clean_tax_code
@@ -161,3 +162,8 @@ class ProductTypeCreate(DeprecatedModelMutation):
instance.product_attributes.set(product_attributes)
if variant_attributes is not None:
instance.variant_attributes.set(variant_attributes)
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_type_created, instance)
diff --git a/saleor/graphql/product/mutations/product_type/product_type_delete.py b/saleor/graphql/product/mutations/product_type/product_type_delete.py
index 0ac8e59515..3029975d8d 100644
--- a/saleor/graphql/product/mutations/product_type/product_type_delete.py
+++ b/saleor/graphql/product/mutations/product_type/product_type_delete.py
@@ -13,6 +13,7 @@ from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PRODUCTS
from ....core.mutations import ModelDeleteMutation
from ....core.types import ProductError
+from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import ProductType
@@ -70,3 +71,8 @@ class ProductTypeDelete(ModelDeleteMutation):
| Q(variantassignments__assignment__product_type_id=instance_pk)
),
).delete()
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_type_deleted, instance)
diff --git a/saleor/graphql/product/mutations/product_type/product_type_update.py b/saleor/graphql/product/mutations/product_type/product_type_update.py
index df173a6648..fa28940f46 100644
--- a/saleor/graphql/product/mutations/product_type/product_type_update.py
+++ b/saleor/graphql/product/mutations/product_type/product_type_update.py
@@ -8,6 +8,7 @@ from .....product.utils.search_helpers import (
)
from ....core import ResolveInfo
from ....core.types import ProductError
+from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import ProductType
from .product_type_create import ProductTypeCreate, ProductTypeInput
@@ -41,7 +42,7 @@ class ProductTypeUpdate(ProductTypeCreate):
super().save(info, instance, cleaned_input)
@classmethod
- def post_save_action(cls, _info: ResolveInfo, instance, cleaned_input):
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
if (
"product_attributes" in cleaned_input
or "variant_attributes" in cleaned_input
@@ -52,3 +53,6 @@ class ProductTypeUpdate(ProductTypeCreate):
)
)
mark_products_search_vector_as_dirty_in_batches(product_ids)
+
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.product_type_updated, instance)
diff --git a/saleor/graphql/product/tests/mutations/test_product_type_create.py b/saleor/graphql/product/tests/mutations/test_product_type_create.py
index 3e0adfdb2d..fa028b0d5c 100644
--- a/saleor/graphql/product/tests/mutations/test_product_type_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_type_create.py
@@ -1,11 +1,18 @@
+import json
+from unittest import mock
from unittest.mock import ANY
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
+from freezegun import freeze_time
from .....attribute import AttributeType
+from .....core.utils.json_serializer import CustomJsonEncoder
from .....product.error_codes import ProductErrorCode
from .....product.models import ProductType
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import get_graphql_content
from ...enums import ProductTypeKindEnum
@@ -142,6 +149,65 @@ def test_product_type_create_mutation(
)
+@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_product_type_create_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_product_types_and_attributes)
+
+ name = "Test product type"
+ slug = "test-product-type"
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "kind": ProductTypeKindEnum.NORMAL.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PRODUCT_TYPE_CREATE_MUTATION, variables)
+ product_type = ProductType.objects.last()
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeCreate"]
+
+ assert not data["errors"]
+ assert data["productType"]
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "name": product_type.name,
+ "slug": product_type.slug,
+ "meta": generate_meta(
+ requestor_data=generate_requestor(
+ SimpleLazyObject(lambda: staff_api_client.user)
+ )
+ ),
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.PRODUCT_TYPE_CREATED,
+ [any_webhook],
+ product_type,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ allow_replica=False,
+ )
+
+
def test_product_type_create_mutation_optional_kind(
staff_api_client, permission_manage_product_types_and_attributes
):
diff --git a/saleor/graphql/product/tests/mutations/test_product_type_delete.py b/saleor/graphql/product/tests/mutations/test_product_type_delete.py
index 9010ec12b8..fa9a84db3f 100644
--- a/saleor/graphql/product/tests/mutations/test_product_type_delete.py
+++ b/saleor/graphql/product/tests/mutations/test_product_type_delete.py
@@ -1,12 +1,19 @@
+import json
+from unittest import mock
from unittest.mock import patch
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
+from freezegun import freeze_time
from prices import Money, TaxedMoney
from .....attribute.utils import associate_attribute_values_to_instance
+from .....core.utils.json_serializer import CustomJsonEncoder
from .....order import OrderStatus
from .....order.models import OrderLine
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import get_graphql_content
PRODUCT_TYPE_DELETE_MUTATION = """
@@ -35,6 +42,59 @@ def test_product_type_delete_mutation(
product_type.refresh_from_db()
+@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_product_type_delete_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_TYPE_DELETE_MUTATION, {"id": product_type_id}
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeDelete"]
+
+ assert data["productType"]["name"] == product_type.name
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": product_type_id,
+ "name": product_type.name,
+ "slug": product_type.slug,
+ "meta": generate_meta(
+ requestor_data=generate_requestor(
+ SimpleLazyObject(lambda: staff_api_client.user)
+ )
+ ),
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.PRODUCT_TYPE_DELETED,
+ [any_webhook],
+ product_type,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ allow_replica=False,
+ )
+
+
@patch("saleor.product.signals.delete_from_storage_task.delay")
def test_product_type_delete_mutation_deletes_also_images(
delete_from_storage_task_mock,
diff --git a/saleor/graphql/product/tests/mutations/test_product_type_update.py b/saleor/graphql/product/tests/mutations/test_product_type_update.py
index f85b023f03..7fe0443f36 100644
--- a/saleor/graphql/product/tests/mutations/test_product_type_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_type_update.py
@@ -1,10 +1,17 @@
+import json
+from unittest import mock
from unittest.mock import patch
import graphene
import pytest
+from django.utils.functional import SimpleLazyObject
+from freezegun import freeze_time
+from .....core.utils.json_serializer import CustomJsonEncoder
from .....product.error_codes import ProductErrorCode
from .....product.models import ProductType
+from .....webhook.event_types import WebhookEventAsyncType
+from .....webhook.payloads import generate_meta, generate_requestor
from ....tests.utils import get_graphql_content
from ...enums import ProductTypeKindEnum
@@ -51,6 +58,64 @@ mutation updateProductType(
"""
+@freeze_time("2022-05-12 12:00:00")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_product_type_update_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_product_types_and_attributes)
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "name": "New name",
+ "hasVariants": product_type.has_variants,
+ "isShippingRequired": product_type.is_shipping_required,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PRODUCT_TYPE_UPDATE_MUTATION, variables)
+ product_type.refresh_from_db()
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeUpdate"]
+
+ assert not data["errors"]
+ assert data["productType"]
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "name": product_type.name,
+ "slug": product_type.slug,
+ "meta": generate_meta(
+ requestor_data=generate_requestor(
+ SimpleLazyObject(lambda: staff_api_client.user)
+ )
+ ),
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.PRODUCT_TYPE_UPDATED,
+ [any_webhook],
+ product_type,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ allow_replica=False,
+ )
+
+
def test_product_type_update_mutation(
staff_api_client,
product_type,
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 10dbe1a682..81263d64b9 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -900,6 +900,50 @@ def test_delete_product_types(
).exists()
+@patch(
+ "saleor.graphql.product.bulk_mutations.product_type_bulk_delete."
+ "get_webhooks_for_event"
+)
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_delete_product_types_trigger_webhooks(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ product_type_list,
+ permission_manage_product_types_and_attributes,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ product_type_count = len(product_type_list)
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("ProductType", product_type.pk)
+ for product_type in product_type_list
+ ]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_TYPE_BULK_DELETE_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeBulkDelete"]
+
+ assert not data["errors"]
+ assert data["count"] == product_type_count
+ assert mocked_webhook_trigger.call_count == product_type_count
+
+
def test_delete_product_types_invalid_object_typed_of_given_ids(
staff_api_client,
product_type_list,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c44367740d..29b25bcde2 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2025,6 +2025,15 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""A product export is completed."""
PRODUCT_EXPORT_COMPLETED
+ """A new product type is created."""
+ PRODUCT_TYPE_CREATED
+
+ """A product type is updated."""
+ PRODUCT_TYPE_UPDATED
+
+ """A product type is deleted."""
+ PRODUCT_TYPE_DELETED
+
"""A new product media is created."""
PRODUCT_MEDIA_CREATED
@@ -2629,6 +2638,15 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""A product export is completed."""
PRODUCT_EXPORT_COMPLETED
+ """A new product type is created."""
+ PRODUCT_TYPE_CREATED
+
+ """A product type is updated."""
+ PRODUCT_TYPE_UPDATED
+
+ """A product type is deleted."""
+ PRODUCT_TYPE_DELETED
+
"""A new product media is created."""
PRODUCT_MEDIA_CREATED
@@ -14247,6 +14265,9 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
PRODUCT_DELETED
PRODUCT_METADATA_UPDATED
PRODUCT_EXPORT_COMPLETED
+ PRODUCT_TYPE_CREATED
+ PRODUCT_TYPE_UPDATED
+ PRODUCT_TYPE_DELETED
PRODUCT_MEDIA_CREATED
PRODUCT_MEDIA_UPDATED
PRODUCT_MEDIA_DELETED
@@ -35822,6 +35843,72 @@ type ProductExportCompleted implements Event @doc(category: "Products") {
export: ExportFile
}
+"""
+Event sent when new product type is created.
+
+Added in Saleor 3.24.
+"""
+type ProductTypeCreated implements Event @doc(category: "Products") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The product type the event relates to."""
+ productType: ProductType
+}
+
+"""
+Event sent when product type is updated.
+
+Added in Saleor 3.24.
+"""
+type ProductTypeUpdated implements Event @doc(category: "Products") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The product type the event relates to."""
+ productType: ProductType
+}
+
+"""
+Event sent when product type is deleted.
+
+Added in Saleor 3.24.
+"""
+type ProductTypeDeleted implements Event @doc(category: "Products") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The product type the event relates to."""
+ productType: ProductType
+}
+
"""Event sent when new product media is created."""
type ProductMediaCreated implements Event @doc(category: "Products") {
"""Time of the event."""
diff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.py
index 0d63608e1d..ec78f59e81 100644
--- a/saleor/graphql/tests/queries/fragments.py
+++ b/saleor/graphql/tests/queries/fragments.py
@@ -349,6 +349,17 @@ fragment PageTypeDetails on PageType{
}
"""
+PRODUCT_TYPE_DETAILS = """
+fragment ProductTypeDetails on ProductType{
+ id
+ name
+ slug
+ kind
+ hasVariants
+ isShippingRequired
+}
+"""
+
PERMISSION_GROUP_DETAILS = """
fragment PermissionGroupDetails on Group{
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 6d186af2e9..7338888b60 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -156,6 +156,9 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.PRODUCT_UPDATED: "A product is updated.",
WebhookEventAsyncType.PRODUCT_DELETED: "A product is deleted.",
WebhookEventAsyncType.PRODUCT_METADATA_UPDATED: "A product metadata is updated.",
+ WebhookEventAsyncType.PRODUCT_TYPE_CREATED: "A new product type is created.",
+ WebhookEventAsyncType.PRODUCT_TYPE_UPDATED: "A product type is updated.",
+ WebhookEventAsyncType.PRODUCT_TYPE_DELETED: "A product type is deleted.",
WebhookEventAsyncType.PRODUCT_MEDIA_CREATED: "A new product media is created.",
WebhookEventAsyncType.PRODUCT_MEDIA_UPDATED: "A product media is updated.",
WebhookEventAsyncType.PRODUCT_MEDIA_DELETED: "A product media is deleted.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 5aa10e1ee3..c649668cac 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -56,6 +56,7 @@ from ..core.descriptions import (
ADDED_IN_321,
ADDED_IN_322,
ADDED_IN_323,
+ ADDED_IN_324,
DEPRECATED_IN_3X_EVENT,
PREVIEW_FEATURE,
)
@@ -904,6 +905,42 @@ class ProductMetadataUpdated(SubscriptionObjectType, ProductBase):
description = "Event sent when product metadata is updated."
+class ProductTypeBase(AbstractType):
+ product_type = graphene.Field(
+ "saleor.graphql.product.types.ProductType",
+ description="The product type the event relates to.",
+ )
+
+ @staticmethod
+ def resolve_product_type(root, _info: ResolveInfo):
+ _, product_type = root
+ return product_type
+
+
+class ProductTypeCreated(SubscriptionObjectType, ProductTypeBase):
+ class Meta:
+ root_type = "ProductType"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "Event sent when new product type is created." + ADDED_IN_324
+
+
+class ProductTypeUpdated(SubscriptionObjectType, ProductTypeBase):
+ class Meta:
+ root_type = "ProductType"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "Event sent when product type is updated." + ADDED_IN_324
+
+
+class ProductTypeDeleted(SubscriptionObjectType, ProductTypeBase):
+ class Meta:
+ root_type = "ProductType"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "Event sent when product type is deleted." + ADDED_IN_324
+
+
class ProductMediaBase(AbstractType):
product_media = graphene.Field(
"saleor.graphql.product.types.ProductMedia",
@@ -3244,6 +3281,9 @@ ASYNC_WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.PRODUCT_DELETED: ProductDeleted,
WebhookEventAsyncType.PRODUCT_METADATA_UPDATED: ProductMetadataUpdated,
WebhookEventAsyncType.PRODUCT_EXPORT_COMPLETED: ProductExportCompleted,
+ WebhookEventAsyncType.PRODUCT_TYPE_CREATED: ProductTypeCreated,
+ WebhookEventAsyncType.PRODUCT_TYPE_UPDATED: ProductTypeUpdated,
+ WebhookEventAsyncType.PRODUCT_TYPE_DELETED: ProductTypeDeleted,
WebhookEventAsyncType.PRODUCT_MEDIA_CREATED: ProductMediaCreated,
WebhookEventAsyncType.PRODUCT_MEDIA_UPDATED: ProductMediaUpdated,
WebhookEventAsyncType.PRODUCT_MEDIA_DELETED: ProductMediaDeleted,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index de702ba398..d30db123df 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1262,6 +1262,33 @@ class BasePlugin:
# Webhook-related functionality will be moved from the plugin to core modules.
product_updated: Callable[["Product", Any, None], Any]
+ # Trigger when product type is created.
+ #
+ # Overwrite this method if you need to trigger specific logic after a product type
+ # is created.
+ #
+ # Note: This method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from the plugin to core modules.
+ product_type_created: Callable[["ProductType", Any], Any]
+
+ # Trigger when product type is deleted.
+ #
+ # Overwrite this method if you need to trigger specific logic after a product type
+ # is deleted.
+ #
+ # Note: This method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from the plugin to core modules.
+ product_type_deleted: Callable[["ProductType", Any, None], Any]
+
+ # Trigger when product type is updated.
+ #
+ # Overwrite this method if you need to trigger specific logic after a product type
+ # is updated.
+ #
+ # Note: This method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from the plugin to core modules.
+ product_type_updated: Callable[["ProductType", Any], Any]
+
# Trigger when product media is created.
#
# Overwrite this method if you need to trigger specific logic after a product media
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index dbbb580161..bc057c652d 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -787,6 +787,34 @@ class PluginsManager(PaymentInterface):
channel_slug=None,
)
+ # Note: this method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from plugin to core modules.
+ def product_type_created(self, product_type: "ProductType"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "product_type_created", default_value, product_type, channel_slug=None
+ )
+
+ # Note: this method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from plugin to core modules.
+ def product_type_updated(self, product_type: "ProductType"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "product_type_updated", default_value, product_type, channel_slug=None
+ )
+
+ # Note: this method is deprecated and will be removed in a future release.
+ # Webhook-related functionality will be moved from plugin to core modules.
+ def product_type_deleted(self, product_type: "ProductType", webhooks=None):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "product_type_deleted",
+ default_value,
+ product_type,
+ webhooks=webhooks,
+ channel_slug=None,
+ )
+
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
def product_media_created(self, media: "ProductMedia"):
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c78365c150..b105010e98 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1865,6 +1865,50 @@ class WebhookPlugin(BasePlugin):
)
return previous_value
+ def _trigger_product_type_event(self, event_type, product_type, webhooks=None):
+ if webhooks := self._get_webhooks_for_event(event_type, webhooks):
+ payload = self._serialize_payload(
+ {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "name": product_type.name,
+ "slug": product_type.slug,
+ "meta": self._generate_meta(),
+ }
+ )
+ self.trigger_webhooks_async(
+ payload, event_type, webhooks, product_type, self.requestor
+ )
+
+ def product_type_created(
+ self, product_type: "ProductType", previous_value: None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_product_type_event(
+ WebhookEventAsyncType.PRODUCT_TYPE_CREATED, product_type
+ )
+ return previous_value
+
+ def product_type_updated(
+ self, product_type: "ProductType", previous_value: None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_product_type_event(
+ WebhookEventAsyncType.PRODUCT_TYPE_UPDATED, product_type
+ )
+ return previous_value
+
+ def product_type_deleted(
+ self, product_type: "ProductType", previous_value: None, webhooks=None
+ ) -> None:
+ if not self.active:
+ return previous_value
+ self._trigger_product_type_event(
+ WebhookEventAsyncType.PRODUCT_TYPE_DELETED, product_type, webhooks=webhooks
+ )
+ return previous_value
+
def product_media_created(
self, media: "ProductMedia", previous_value: None
) -> None:
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index 46ab1d9cc5..b18aa97abb 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -14,6 +14,7 @@ from ..permission.enums import (
PageTypePermissions,
PaymentPermissions,
ProductPermissions,
+ ProductTypePermissions,
ShippingPermissions,
SitePermissions,
)
@@ -130,6 +131,10 @@ class WebhookEventAsyncType:
PRODUCT_METADATA_UPDATED = "product_metadata_updated"
PRODUCT_EXPORT_COMPLETED = "product_export_completed"
+ PRODUCT_TYPE_CREATED = "product_type_created"
+ PRODUCT_TYPE_UPDATED = "product_type_updated"
+ PRODUCT_TYPE_DELETED = "product_type_deleted"
+
PRODUCT_MEDIA_CREATED = "product_media_created"
PRODUCT_MEDIA_UPDATED = "product_media_updated"
PRODUCT_MEDIA_DELETED = "product_media_deleted"
@@ -587,6 +592,18 @@ class WebhookEventAsyncType:
"name": "Product export completed",
"permission": ProductPermissions.MANAGE_PRODUCTS,
},
+ PRODUCT_TYPE_CREATED: {
+ "name": "Product type created",
+ "permission": ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,
+ },
+ PRODUCT_TYPE_UPDATED: {
+ "name": "Product type updated",
+ "permission": ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,
+ },
+ PRODUCT_TYPE_DELETED: {
+ "name": "Product type deleted",
+ "permission": ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,
+ },
PRODUCT_MEDIA_CREATED: {
"name": "Product media created",
"permission": ProductPermissions.MANAGE_PRODUCTS,
diff --git a/saleor/webhook/tests/fixtures/subscription_webhooks.py b/saleor/webhook/tests/fixtures/subscription_webhooks.py
index d31c542683..c6f485b0bb 100644
--- a/saleor/webhook/tests/fixtures/subscription_webhooks.py
+++ b/saleor/webhook/tests/fixtures/subscription_webhooks.py
@@ -879,6 +879,27 @@ def subscription_page_type_deleted_webhook(subscription_webhook):
)
+def subscription_product_type_created_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.PRODUCT_TYPE_CREATED, WebhookEventAsyncType.PRODUCT_TYPE_CREATED
+ )
+
+
+def subscription_product_type_updated_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.PRODUCT_TYPE_UPDATED, WebhookEventAsyncType.PRODUCT_TYPE_UPDATED
+ )
+
+
+def subscription_product_type_deleted_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.PRODUCT_TYPE_DELETED, WebhookEventAsyncType.PRODUCT_TYPE_DELETED
+ )
+
+
@pytest.fixture
def subscription_permission_group_created_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/webhook/tests/subscription_webhooks/payloads.py b/saleor/webhook/tests/subscription_webhooks/payloads.py
index 4cd0d7bae4..7e33b8c65f 100644
--- a/saleor/webhook/tests/subscription_webhooks/payloads.py
+++ b/saleor/webhook/tests/subscription_webhooks/payloads.py
@@ -304,6 +304,23 @@ def generate_page_type_payload(page_type, app):
}
+def generate_product_type_payload(product_type, app):
+ return {
+ "recipient": {
+ "id": graphene.Node.to_global_id("App", app.pk),
+ "name": app.name,
+ },
+ "productType": {
+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),
+ "name": product_type.name,
+ "slug": product_type.slug,
+ "kind": product_type.kind.upper(),
+ "hasVariants": product_type.has_variants,
+ "isShippingRequired": product_type.is_shipping_required,
+ },
+ }
+
+
def generate_permission_group_payload(group, app):
return {
"recipient": {
diff --git a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
index e91b7535eb..d46e81eacb 100644
--- a/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -2283,6 +2283,63 @@ PAGE_TYPE_DELETED = (
"""
)
+PRODUCT_TYPE_CREATED = (
+ fragments.PRODUCT_TYPE_DETAILS
+ + fragments.RECIPIENT_APP_DETAILS
+ + """
+ subscription{
+ event{
+ recipient{
+ ...Recipient
+ }
+ ...on ProductTypeCreated{
+ productType{
+ ...ProductTypeDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+PRODUCT_TYPE_UPDATED = (
+ fragments.PRODUCT_TYPE_DETAILS
+ + fragments.RECIPIENT_APP_DETAILS
+ + """
+ subscription{
+ event{
+ recipient{
+ ...Recipient
+ }
+ ...on ProductTypeUpdated{
+ productType{
+ ...ProductTypeDetails
+ }
+ }
+ }
+ }
+"""
+)
+
+PRODUCT_TYPE_DELETED = (
+ fragments.PRODUCT_TYPE_DETAILS
+ + fragments.RECIPIENT_APP_DETAILS
+ + """
+ subscription{
+ event{
+ recipient{
+ ...Recipient
+ }
+ ...on ProductTypeDeleted{
+ productType{
+ ...ProductTypeDetails
+ }
+ }
+ }
+ }
+"""
+)
+
PERMISSION_GROUP_CREATED = (
fragments.PERMISSION_GROUP_DETAILS
+ fragments.RECIPIENT_APP_DETAILS
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 0742d5b731..95d187d766 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -43,6 +43,7 @@ from .payloads import (
generate_page_payload,
generate_page_type_payload,
generate_permission_group_payload,
+ generate_product_type_payload,
generate_promotion_payload,
generate_promotion_rule_payload,
generate_sale_payload,
@@ -2576,6 +2577,67 @@ def test_page_type_deleted(page_type, subscription_page_type_deleted_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_product_type_created(product_type, subscription_product_type_created_webhook):
+ # given
+ webhooks = [subscription_product_type_created_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_TYPE_CREATED
+ expected_payload = json.dumps(
+ generate_product_type_payload(
+ product_type, subscription_product_type_created_webhook.app
+ )
+ )
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, product_type, webhooks)
+
+ # then
+ assert deliveries[0].payload.get_payload() == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_type_updated(product_type, subscription_product_type_updated_webhook):
+ # given
+ webhooks = [subscription_product_type_updated_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_TYPE_UPDATED
+ expected_payload = json.dumps(
+ generate_product_type_payload(
+ product_type, subscription_product_type_updated_webhook.app
+ )
+ )
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, product_type, webhooks)
+
+ # then
+ assert deliveries[0].payload.get_payload() == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_product_type_deleted(product_type, subscription_product_type_deleted_webhook):
+ # given
+ product_type_id = product_type.id
+ product_type.delete()
+ product_type.id = product_type_id
+
+ webhooks = [subscription_product_type_deleted_webhook]
+ event_type = WebhookEventAsyncType.PRODUCT_TYPE_DELETED
+ expected_payload = json.dumps(
+ generate_product_type_payload(
+ product_type, subscription_product_type_deleted_webhook.app
+ )
+ )
+
+ # when
+ deliveries = create_deliveries_for_subscriptions(event_type, product_type, webhooks)
+
+ # then
+ assert deliveries[0].payload.get_payload() == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_permission_group_created(
permission_group_manage_users, subscription_permission_group_created_webhook
):