Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
New events related to attributes changes (#9991)
SzymJ32cb3242cf31
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02734ff9a1..c3e0d2cda5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add webhooks `PAGE_TYPE_CREATED`, `PAGE_TYPE_UPDATED` and `PAGE_TYPE_DELETED` - #9859 by @SzymJ- Add webhooks `ADDRESS_CREATED`, `ADDRESS_UPDATED` and `ADDRESS_DELETED` - #9860 by @SzymJ- Add webhooks `STAFF_CREATED`, `STAFF_UPDATED` and `STAFF_DELETED` - #9949 by @SzymJ+- Add webhooks `ATTRIBUTE_CREATED`, `ATTRIBUTE_UPDATED` and `ATTRIBUTE_DELETED` - #9991 by @SzymJ- Fix returning errors in subscription webhooks payloads - #9905 by @SzymJ# 3.4.0diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex d97be6f75f..df2da2c14f 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -62,6 +62,13 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):).values_list("id", flat=True)return list(product_ids)+ @classmethod+ def bulk_action(cls, info, queryset):+ attributes = list(queryset)+ queryset.delete()+ for attribute in attributes:+ info.context.plugins.attribute_deleted(attribute)+class AttributeValueBulkDelete(ModelBulkDeleteMutation):class Arguments:@@ -91,6 +98,13 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):)return response+ @classmethod+ def bulk_action(cls, info, queryset):+ attributes = {value.attribute for value in queryset}+ queryset.delete()+ for attribute in attributes:+ info.context.plugins.attribute_updated(attribute)+@classmethoddef get_product_ids_to_update(cls, value_pks):assigned_product_values = models.AssignedProductAttributeValue.objects.filter(diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex 14edf3a654..471647eac3 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -518,10 +518,14 @@ class AttributeCreate(AttributeMixin, ModelMutation):# Commit itinstance.save()cls._save_m2m(info, instance, cleaned_input)-+ cls.post_save_action(info, instance, cleaned_input)# Return the attribute that was createdreturn AttributeCreate(attribute=instance)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.attribute_created(instance)+class AttributeUpdate(AttributeMixin, ModelMutation):# Needed by AttributeMixin,@@ -583,10 +587,15 @@ class AttributeUpdate(AttributeMixin, ModelMutation):# Commit itinstance.save()cls._save_m2m(info, instance, cleaned_input)+ cls.post_save_action(info, instance, cleaned_input)# Return the attribute that was createdreturn AttributeUpdate(attribute=instance)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.attribute_updated(instance)+class AttributeDelete(ModelDeleteMutation):class Arguments:@@ -600,6 +609,10 @@ class AttributeDelete(ModelDeleteMutation):error_type_class = AttributeErrorerror_type_field = "attribute_errors"+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.attribute_deleted(instance)+def validate_value_is_unique(attribute: models.Attribute, value: models.AttributeValue):"""Check if the attribute value is unique within the attribute it belongs to."""@@ -683,8 +696,13 @@ class AttributeValueCreate(AttributeMixin, ModelMutation):instance.save()cls._save_m2m(info, instance, cleaned_input)+ cls.post_save_action(info, instance, cleaned_input)return AttributeValueCreate(attribute=attribute, attributeValue=instance)+ @classmethod+ def post_save_action(cls, info, instance, cleaned_input):+ info.context.plugins.attribute_updated(instance.attribute)+class AttributeValueUpdate(AttributeValueCreate):attribute = graphene.Field(Attribute, description="The updated attribute.")@@ -727,7 +745,6 @@ class AttributeValueUpdate(AttributeValueCreate):@classmethoddef post_save_action(cls, info, instance, cleaned_input):- super().post_save_action(info, instance, cleaned_input)variants = product_models.ProductVariant.objects.filter(Exists(instance.variantassignments.filter(variant_id=OuterRef("id"))))@@ -736,6 +753,7 @@ class AttributeValueUpdate(AttributeValueCreate):| Q(Exists(variants.filter(product_id=OuterRef("id")))))update_products_search_vector(products)+ info.context.plugins.attribute_updated(instance.attribute)class AttributeValueDelete(ModelDeleteMutation):@@ -761,6 +779,7 @@ class AttributeValueDelete(ModelDeleteMutation):update_products_search_vector(product_models.Product.objects.filter(id__in=product_ids))+ info.context.plugins.attribute_updated(instance.attribute)return response@classmethod@@ -845,4 +864,5 @@ class AttributeReorderValues(BaseMutation):with traced_atomic_transaction():perform_reordering(values_m2m, operations)attribute.refresh_from_db(fields=["values"])+ info.context.plugins.attribute_updated(attribute)return AttributeReorderValues(attribute=attribute)diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex a5f937f799..208325d260 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -1,7 +1,15 @@+from unittest import mock++import grapheneimport pytest+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugify+from freezegun import freeze_timefrom .....attribute.error_codes import AttributeErrorCode+from .....attribute.models import Attribute+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....core.enums import MeasurementUnitsEnumfrom ....tests.utils import get_graphql_contentfrom ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum@@ -102,6 +110,67 @@ def test_create_attribute_and_attribute_values(assert data["attribute"]["choices"]["edges"][0]["node"]["slug"] == slugify(name)+@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_create_attribute_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ attribute_name = "Example name"+ name = "Value name"+ variables = {+ "input": {+ "name": attribute_name,+ "values": [{"name": name}],+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ CREATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[+ permission_manage_product_types_and_attributes,+ permission_manage_products,+ ],+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeCreate"]+ attribute = Attribute.objects.last()++ # then+ assert not data["errors"]+ assert data["attribute"]++ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", attribute.id),+ "name": attribute.name,+ "slug": attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_CREATED,+ [any_webhook],+ attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_create_numeric_attribute_and_attribute_values(staff_api_client,permission_manage_product_types_and_attributes,diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.pyindex 11ec094b34..50c9bde2e8 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py@@ -1,6 +1,12 @@+from unittest import mock+import grapheneimport pytest+from django.utils.functional import SimpleLazyObject+from freezegun import freeze_time+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import get_graphql_contentATTRIBUTE_DELETE_MUTATION = """@@ -43,6 +49,56 @@ def test_delete_attribute(attribute.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_delete_attribute_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ product_type,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ node_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ variables = {"id": node_id}++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeDelete"]++ # then+ assert not data["errors"]+ assert data["attribute"]["id"] == variables["id"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "name": color_attribute.name,+ "slug": color_attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_DELETED,+ [any_webhook],+ color_attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_delete_file_attribute(staff_api_client,file_attribute,diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.pyindex 41480bbaa4..5e18847be8 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py@@ -1,6 +1,12 @@+from unittest import mock+import graphene+from django.utils.functional import SimpleLazyObject+from freezegun import freeze_timefrom .....attribute.models import AttributeValue+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import get_graphql_contentATTRIBUTE_VALUES_REORDER_MUTATION = """@@ -139,3 +145,75 @@ def test_sort_values_within_attribute(actual_order.append(int(gql_attr_id))assert actual_order == expected_order+++@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_sort_values_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ AttributeValue.objects.create(attribute=color_attribute, name="Green", slug="green")+ values = list(color_attribute.values.all())+ assert len(values) == 3++ staff_api_client.user.user_permissions.add(+ permission_manage_product_types_and_attributes+ )++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ m2m_values = color_attribute.values+ m2m_values.set(values)++ assert values == sorted(+ values, key=lambda o: o.sort_order if o.sort_order is not None else o.pk+ ), "The values are not properly ordered"++ variables = {+ "attributeId": attribute_id,+ "moves": [+ {+ "id": graphene.Node.to_global_id("AttributeValue", values[0].pk),+ "sortOrder": +1,+ },+ {+ "id": graphene.Node.to_global_id("AttributeValue", values[2].pk),+ "sortOrder": -1,+ },+ ],+ }++ # when+ content = get_graphql_content(+ staff_api_client.post_graphql(ATTRIBUTE_VALUES_REORDER_MUTATION, variables)+ )["data"]["attributeReorderValues"]++ # then+ assert not content["errors"]+ assert content["attribute"]["id"] == attribute_id+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "name": color_attribute.name,+ "slug": color_attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ [any_webhook],+ color_attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex e00a69a700..ba138a0e3a 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -1,8 +1,14 @@+from unittest import mock+import grapheneimport pytest+from django.utils.functional import SimpleLazyObject+from freezegun import freeze_timefrom .....attribute.error_codes import AttributeErrorCodefrom .....attribute.models import Attribute+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....core.enums import MeasurementUnitsEnumfrom ....tests.utils import get_graphql_content@@ -71,6 +77,60 @@ def test_update_attribute_name(assert data["attribute"]["productTypes"]["edges"] == []+@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_update_attribute_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ color_attribute,+ permission_manage_product_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ new_name = "Wings name"+ node_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ variables = {+ "input": {"name": new_name, "addValues": [], "removeValues": []},+ "id": node_id,+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )+ content = get_graphql_content(response)+ color_attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]++ # then+ assert not data["errors"]+ assert data["attribute"]["name"] == new_name+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "name": new_name,+ "slug": color_attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ [any_webhook],+ color_attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_update_attribute_remove_and_add_values(staff_api_client, color_attribute, permission_manage_product_types_and_attributes):diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.pyindex 3e0dfaf776..f8e0d0848b 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py@@ -1,10 +1,16 @@+from unittest import mock+import grapheneimport pytestfrom django.core.exceptions import ValidationError+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugify+from freezegun import freeze_timefrom .....attribute.error_codes import AttributeErrorCodefrom .....attribute.models import AttributeValue+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import get_graphql_contentfrom ...mutations import validate_value_is_unique@@ -90,6 +96,56 @@ def test_create_attribute_value(]+@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_create_attribute_value_trigger_webhooks(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ color_attribute,+ permission_manage_products,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ name = "test name"+ variables = {"name": name, "attributeId": attribute_id}++ # when+ response = staff_api_client.post_graphql(+ CREATE_ATTRIBUTE_VALUE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeValueCreate"]++ # then+ assert not data["errors"]+ assert data["attributeValue"]+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "name": color_attribute.name,+ "slug": color_attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ [any_webhook],+ color_attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_create_swatch_attribute_value_with_value(staff_api_client, swatch_attribute, permission_manage_products):diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex 8451e47964..7f365d60c1 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -1,7 +1,13 @@+from unittest import mock+import grapheneimport pytest+from django.utils.functional import SimpleLazyObject+from freezegun import freeze_timefrom .....attribute.utils import associate_attribute_values_to_instance+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorATTRIBUTE_VALUE_DELETE_MUTATION = """mutation AttributeValueDelete($id: ID!) {@@ -37,6 +43,53 @@ def test_delete_attribute_value(value.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_delete_attribute_value_trigger_webhooks(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ color_attribute,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ value = color_attribute.values.get(name="Red")+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ variables = {"id": node_id}++ # when+ staff_api_client.post_graphql(+ ATTRIBUTE_VALUE_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )++ # then+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),+ "name": color_attribute.name,+ "slug": color_attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ [any_webhook],+ color_attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_delete_file_attribute_value(staff_api_client,file_attribute,diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex e1d6594e33..bbcecfcb53 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -1,9 +1,15 @@+from unittest import mock+import grapheneimport pytest+from django.utils.functional import SimpleLazyObjectfrom django.utils.text import slugify+from freezegun import freeze_timefrom .....attribute.error_codes import AttributeErrorCodefrom .....attribute.utils import associate_attribute_values_to_instance+from .....webhook.event_types import WebhookEventAsyncType+from .....webhook.payloads import generate_meta, generate_requestorfrom ....tests.utils import get_graphql_contentUPDATE_ATTRIBUTE_VALUE_MUTATION = """@@ -67,6 +73,59 @@ def test_update_attribute_value(]+@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_update_attribute_value_trigger_webhooks(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ pink_attribute_value,+ permission_manage_product_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ value = pink_attribute_value+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ name = "Crimson name"+ variables = {"input": {"name": name}, "id": node_id}++ # when+ response = staff_api_client.post_graphql(+ UPDATE_ATTRIBUTE_VALUE_MUTATION,+ variables,+ permissions=[permission_manage_product_types_and_attributes],+ )+ content = get_graphql_content(response)+ data = content["data"]["attributeValueUpdate"]+ value.refresh_from_db()+ attribute = value.attribute++ # then+ assert not data["errors"]+ assert data["attributeValue"]["name"] == name == value.name+ mocked_webhook_trigger.assert_called_once_with(+ {+ "id": graphene.Node.to_global_id("Attribute", attribute.id),+ "name": attribute.name,+ "slug": attribute.slug,+ "meta": generate_meta(+ requestor_data=generate_requestor(+ SimpleLazyObject(lambda: staff_api_client.user)+ )+ ),+ },+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ [any_webhook],+ attribute,+ SimpleLazyObject(lambda: staff_api_client.user),+ )++def test_update_attribute_value_name_not_unique(staff_api_client,pink_attribute_value,diff --git a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.pyindex 322919d1bb..7349d8de5a 100644--- a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py@@ -1,3 +1,5 @@+from unittest import mock+import grapheneimport pytest@@ -52,6 +54,40 @@ def test_delete_attributes().exists()[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_delete_attributes_trigger_webhooks(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ product_type_attribute_list,+ permission_manage_page_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ variables = {+ "ids": [+ graphene.Node.to_global_id("Attribute", attr.id)+ for attr in product_type_attribute_list+ ]+ }+ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_BULK_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_page_types_and_attributes],+ )+ content = get_graphql_content(response)++ # then+ assert content["data"]["attributeBulkDelete"]["count"] == 3+ assert mocked_webhook_trigger.call_count == 3++def test_delete_attributes_products_search_document_updated(staff_api_client,product_type_attribute_list,@@ -136,6 +172,42 @@ def test_delete_attribute_values().exists()[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")+def test_delete_attribute_values_trigger_webhook(+ mocked_webhook_trigger,+ mocked_get_webhooks_for_event,+ any_webhook,+ staff_api_client,+ attribute_value_list,+ permission_manage_page_types_and_attributes,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]++ attributes = {value.attribute for value in attribute_value_list}+ variables = {+ "ids": [+ graphene.Node.to_global_id("AttributeValue", val.id)+ for val in attribute_value_list+ ]+ }++ # when+ response = staff_api_client.post_graphql(+ ATTRIBUTE_VALUE_BULK_DELETE_MUTATION,+ variables,+ permissions=[permission_manage_page_types_and_attributes],+ )+ content = get_graphql_content(response)++ # then+ assert content["data"]["attributeValueBulkDelete"]["count"] == 3+ assert mocked_webhook_trigger.call_count == len(attributes)++def test_delete_attribute_values_search_document_updated(staff_api_client,product_list,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex c3d9a2f7b0..b5f1d65260 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1348,6 +1348,15 @@ enum WebhookEventTypeEnum {"""An app status is changed."""APP_STATUS_CHANGED+ """A new attribute is created."""+ ATTRIBUTE_CREATED++ """An attribute is updated."""+ ATTRIBUTE_UPDATED++ """An attribute is deleted."""+ ATTRIBUTE_DELETED+"""A new category created."""CATEGORY_CREATED@@ -1622,6 +1631,15 @@ enum WebhookEventTypeAsyncEnum {"""An app status is changed."""APP_STATUS_CHANGED+ """A new attribute is created."""+ ATTRIBUTE_CREATED++ """An attribute is updated."""+ ATTRIBUTE_UPDATED++ """An attribute is deleted."""+ ATTRIBUTE_DELETED+"""A new category created."""CATEGORY_CREATED@@ -2298,6 +2316,9 @@ enum WebhookSampleEventTypeEnum {APP_UPDATEDAPP_DELETEDAPP_STATUS_CHANGED+ ATTRIBUTE_CREATED+ ATTRIBUTE_UPDATED+ ATTRIBUTE_DELETEDCATEGORY_CREATEDCATEGORY_UPDATEDCATEGORY_DELETED@@ -20891,6 +20912,75 @@ type AppStatusChanged implements Event {app: App}+type AttributeCreated implements Event {+ """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 attribute the event relates to.++ Added in Saleor 3.5.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ attribute: Attribute+}++type AttributeUpdated implements Event {+ """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 attribute the event relates to.++ Added in Saleor 3.5.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ attribute: Attribute+}++type AttributeDeleted implements Event {+ """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 attribute the event relates to.++ Added in Saleor 3.5.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ attribute: Attribute+}+type CategoryCreated implements Event {"""Time of the event."""issuedAt: DateTimediff --git a/saleor/graphql/tests/queries/fragments.py b/saleor/graphql/tests/queries/fragments.pyindex fb7c2da497..19a617d344 100644--- a/saleor/graphql/tests/queries/fragments.py+++ b/saleor/graphql/tests/queries/fragments.py@@ -384,3 +384,12 @@ MENU_ITEM_DETAILS = """}}"""++ATTRIBUTE_DETAILS = """+fragment AttributeDetails on Attribute {+ name+ slug+ type+ inputType+}+"""diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex c299bfd2dc..2528d9039d 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -30,6 +30,9 @@ WEBHOOK_EVENT_DESCRIPTION = {WebhookEventAsyncType.APP_UPDATED: "An app updated.",WebhookEventAsyncType.APP_DELETED: "An app deleted.",WebhookEventAsyncType.APP_STATUS_CHANGED: "An app status is changed.",+ WebhookEventAsyncType.ATTRIBUTE_CREATED: "A new attribute is created.",+ WebhookEventAsyncType.ATTRIBUTE_UPDATED: "An attribute is updated.",+ WebhookEventAsyncType.ATTRIBUTE_DELETED: "An attribute is deleted.",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.pyindex fb3284590a..9badb26b77 100644--- a/saleor/graphql/webhook/subscription_types.py+++ b/saleor/graphql/webhook/subscription_types.py@@ -77,6 +77,9 @@ class Event(graphene.Interface):WebhookEventAsyncType.APP_UPDATED: AppUpdated,WebhookEventAsyncType.APP_DELETED: AppDeleted,WebhookEventAsyncType.APP_STATUS_CHANGED: AppStatusChanged,+ WebhookEventAsyncType.ATTRIBUTE_CREATED: AttributeCreated,+ WebhookEventAsyncType.ATTRIBUTE_UPDATED: AttributeUpdated,+ WebhookEventAsyncType.ATTRIBUTE_DELETED: AttributeDeleted,WebhookEventAsyncType.CATEGORY_CREATED: CategoryCreated,WebhookEventAsyncType.CATEGORY_UPDATED: CategoryUpdated,WebhookEventAsyncType.CATEGORY_DELETED: CategoryDeleted,@@ -242,6 +245,35 @@ class AppStatusChanged(ObjectType, AppBase):interfaces = (Event,)+class AttributeBase(AbstractType):+ attribute = graphene.Field(+ "saleor.graphql.attribute.types.Attribute",+ description="The attribute the event relates to."+ + ADDED_IN_35+ + PREVIEW_FEATURE,+ )++ @staticmethod+ def resolve_attribute(root, _info):+ _, attribute = root+ return attribute+++class AttributeCreated(ObjectType, AttributeBase):+ class Meta:+ interfaces = (Event,)+++class AttributeUpdated(ObjectType, AttributeBase):+ class Meta:+ interfaces = (Event,)+++class AttributeDeleted(ObjectType, AttributeBase):+ class Meta:+ interfaces = (Event,)++class CategoryBase(AbstractType):category = graphene.Field("saleor.graphql.product.types.Category",@@ -1050,6 +1082,9 @@ SUBSCRIPTION_EVENTS_TYPES = [AppUpdated,AppDeleted,AppStatusChanged,+ AttributeCreated,+ AttributeUpdated,+ AttributeDeleted,CategoryCreated,CategoryUpdated,CategoryDeleted,diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 746e90b0ae..da45239fe7 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -29,6 +29,7 @@ if TYPE_CHECKING:# flake8: noqafrom ..account.models import Address, Userfrom ..app.models import App+ from ..attribute.models import Attributefrom ..channel.models import Channelfrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkout@@ -188,6 +189,24 @@ class BasePlugin:[Union["Product", "ProductType"], Union[str, NoneType], Any], Any]+ # Trigger when attribute is created.+ #+ # Overwrite this method if you need to trigger specific logic after an attribute is+ # installed.+ attribute_created: Callable[["Attribute", None], None]++ # Trigger when attribute is deleted.+ #+ # Overwrite this method if you need to trigger specific logic after an attribute is+ # deleted.+ attribute_deleted: Callable[["Attribute", None], None]++ # Trigger when attribute is updated.+ #+ # Overwrite this method if you need to trigger specific logic after an attribute is+ # updated.+ attribute_updated: Callable[["Attribute", None], None]+# Authenticate user which should be assigned to the request.## Overwrite this method if the plugin handles authentication flow.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex e68b8d2b05..94931c2eaa 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -40,6 +40,7 @@ if TYPE_CHECKING:# flake8: noqafrom ..account.models import Address, Userfrom ..app.models import App+ from ..attribute.models import Attributefrom ..checkout.fetch import CheckoutInfo, CheckoutLineInfofrom ..checkout.models import Checkoutfrom ..core.middleware import Requestor@@ -863,6 +864,24 @@ class PluginsManager(PaymentInterface):default_value = Nonereturn self.__run_method_on_plugins("app_status_changed", default_value, app)+ def attribute_created(self, attribute: "Attribute"):+ default_value = None+ return self.__run_method_on_plugins(+ "attribute_created", default_value, attribute+ )++ def attribute_updated(self, attribute: "Attribute"):+ default_value = None+ return self.__run_method_on_plugins(+ "attribute_updated", default_value, attribute+ )++ def attribute_deleted(self, attribute: "Attribute"):+ default_value = None+ return self.__run_method_on_plugins(+ "attribute_deleted", default_value, attribute+ )+def category_created(self, category: "Category"):default_value = Nonereturn self.__run_method_on_plugins("category_created", default_value, category)diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex f5781d3a3d..9e2a863a02 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -51,6 +51,7 @@ from .utils import (if TYPE_CHECKING:from ...account.models import Address, User+ from ...attribute.models import Attributefrom ...channel.models import Channelfrom ...checkout.models import Checkoutfrom ...discount.models import Sale, Voucher@@ -154,6 +155,39 @@ class WebhookPlugin(BasePlugin):return previous_valueself._trigger_app_event(WebhookEventAsyncType.APP_STATUS_CHANGED, app)+ def _trigger_attribute_event(self, event_type, attribute):+ if webhooks := get_webhooks_for_event(event_type):+ payload = {+ "id": graphene.Node.to_global_id("Attribute", attribute.id),+ "name": attribute.name,+ "slug": attribute.slug,+ "meta": self._generate_meta(),+ }+ trigger_webhooks_async(+ payload, event_type, webhooks, attribute, self.requestor+ )++ def attribute_created(self, attribute: "Attribute", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_attribute_event(+ WebhookEventAsyncType.ATTRIBUTE_CREATED, attribute+ )++ def attribute_updated(self, attribute: "Attribute", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_attribute_event(+ WebhookEventAsyncType.ATTRIBUTE_UPDATED, attribute+ )++ def attribute_deleted(self, attribute: "Attribute", previous_value: None) -> None:+ if not self.active:+ return previous_value+ self._trigger_attribute_event(+ WebhookEventAsyncType.ATTRIBUTE_DELETED, attribute+ )+def __trigger_category_event(self, event_type, category):if webhooks := get_webhooks_for_event(event_type):payload = {diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.pyindex d596ba0e3b..1840a3d9f7 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py@@ -70,6 +70,27 @@ def subscription_app_status_changed_webhook(subscription_webhook):)+def subscription_attribute_created_webhook(subscription_webhook):+ return subscription_webhook(+ subscription_queries.ATTRIBUTE_CREATED, WebhookEventAsyncType.ATTRIBUTE_CREATED+ )+++def subscription_attribute_updated_webhook(subscription_webhook):+ return subscription_webhook(+ subscription_queries.ATTRIBUTE_UPDATED, WebhookEventAsyncType.ATTRIBUTE_UPDATED+ )+++def subscription_attribute_deleted_webhook(subscription_webhook):+ return subscription_webhook(+ subscription_queries.ATTRIBUTE_DELETED, WebhookEventAsyncType.ATTRIBUTE_DELETED+ )++@pytest.fixturedef subscription_category_created_webhook(subscription_webhook):return subscription_webhook(diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.pyindex 707687af68..6022157958 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/payloads.py@@ -4,6 +4,7 @@ import graphenefrom django.utils import timezonefrom ..... import __version__+from .....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnumfrom .....product.models import Product@@ -20,6 +21,19 @@ def generate_app_payload(app, app_global_id):)+def generate_attribute_payload(attribute):+ return json.dumps(+ {+ "attribute": {+ "name": attribute.name,+ "slug": attribute.slug,+ "type": AttributeTypeEnum.get(attribute.type).name,+ "inputType": AttributeInputTypeEnum.get(attribute.input_type).name,+ }+ }+ )++def generate_taxed_money_payload(taxed_money):return {"currency": taxed_money.currency,diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.pyindex 1e2c186797..06a23ebd0a 100644--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py@@ -111,6 +111,54 @@ APP_STATUS_CHANGED = ()+ATTRIBUTE_CREATED = (+ fragments.ATTRIBUTE_DETAILS+ + """+ subscription{+ event{+ ...on AttributeCreated{+ attribute{+ ...AttributeDetails+ }+ }+ }+ }+"""+)+++ATTRIBUTE_UPDATED = (+ fragments.ATTRIBUTE_DETAILS+ + """+ subscription{+ event{+ ...on AttributeUpdated{+ attribute{+ ...AttributeDetails+ }+ }+ }+ }+"""+)+++ATTRIBUTE_DELETED = (+ fragments.ATTRIBUTE_DETAILS+ + """+ subscription{+ event{+ ...on AttributeDeleted{+ attribute{+ ...AttributeDetails+ }+ }+ }+ }+"""+)++GIFT_CARD_CREATED = (fragments.GIFT_CARD_DETAILS+ """diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.pyindex b5348a3963..03befa4229 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@@ -18,6 +18,7 @@ from . import subscription_queriesfrom .payloads import (generate_address_payload,generate_app_payload,+ generate_attribute_payload,generate_category_payload,generate_collection_payload,generate_customer_payload,@@ -198,6 +199,62 @@ def test_app_status_changed(status, app, subscription_app_status_changed_webhookassert deliveries[0].webhook == webhooks[0]+def test_attribute_created(color_attribute, subscription_attribute_created_webhook):+ # given+ webhooks = [subscription_attribute_created_webhook]+ event_type = WebhookEventAsyncType.ATTRIBUTE_CREATED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, color_attribute, webhooks+ )++ # then+ expected_payload = generate_attribute_payload(color_attribute)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_attribute_updated(color_attribute, subscription_attribute_updated_webhook):+ # given+ webhooks = [subscription_attribute_updated_webhook]+ event_type = WebhookEventAsyncType.ATTRIBUTE_UPDATED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, color_attribute, webhooks+ )++ # then+ expected_payload = generate_attribute_payload(color_attribute)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]+++def test_attribute_deleted(color_attribute, subscription_attribute_deleted_webhook):+ # given+ webhooks = [subscription_attribute_deleted_webhook]++ id = color_attribute.id+ color_attribute.delete()+ color_attribute.id = id++ event_type = WebhookEventAsyncType.ATTRIBUTE_DELETED++ # when+ deliveries = create_deliveries_for_subscriptions(+ event_type, color_attribute, webhooks+ )++ # then+ expected_payload = generate_attribute_payload(color_attribute)+ assert deliveries[0].payload.payload == expected_payload+ assert len(deliveries) == len(webhooks)+ assert deliveries[0].webhook == webhooks[0]++def test_category_created(categories_tree_with_published_products,subscription_category_created_webhook,diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.pyindex 3ff04faade..faffd18f08 100644--- a/saleor/webhook/event_types.py+++ b/saleor/webhook/event_types.py@@ -28,6 +28,10 @@ class WebhookEventAsyncType:APP_DELETED = "app_deleted"APP_STATUS_CHANGED = "app_status_changed"+ ATTRIBUTE_CREATED = "attribute_created"+ ATTRIBUTE_UPDATED = "attribute_updated"+ ATTRIBUTE_DELETED = "attribute_deleted"+CATEGORY_CREATED = "category_created"CATEGORY_UPDATED = "category_updated"CATEGORY_DELETED = "category_deleted"@@ -138,6 +142,9 @@ class WebhookEventAsyncType:APP_UPDATED: "App updated",APP_DELETED: "App deleted",APP_STATUS_CHANGED: "App status changed",+ ATTRIBUTE_CREATED: "Attribute created",+ ATTRIBUTE_UPDATED: "Attribute updated",+ ATTRIBUTE_DELETED: "Attribute deleted",CATEGORY_CREATED: "Category created",CATEGORY_UPDATED: "Category updated",CATEGORY_DELETED: "Category deleted",@@ -224,6 +231,9 @@ class WebhookEventAsyncType:(APP_UPDATED, DISPLAY_LABELS[APP_UPDATED]),(APP_DELETED, DISPLAY_LABELS[APP_DELETED]),(APP_STATUS_CHANGED, DISPLAY_LABELS[APP_STATUS_CHANGED]),+ (ATTRIBUTE_CREATED, DISPLAY_LABELS[ATTRIBUTE_CREATED]),+ (ATTRIBUTE_UPDATED, DISPLAY_LABELS[ATTRIBUTE_UPDATED]),+ (ATTRIBUTE_DELETED, DISPLAY_LABELS[ATTRIBUTE_DELETED]),(CATEGORY_CREATED, DISPLAY_LABELS[CATEGORY_CREATED]),(CATEGORY_UPDATED, DISPLAY_LABELS[CATEGORY_UPDATED]),(CATEGORY_DELETED, DISPLAY_LABELS[CATEGORY_DELETED]),@@ -311,6 +321,9 @@ class WebhookEventAsyncType:APP_UPDATED: AppPermission.MANAGE_APPS,APP_DELETED: AppPermission.MANAGE_APPS,APP_STATUS_CHANGED: AppPermission.MANAGE_APPS,+ ATTRIBUTE_CREATED: None,+ ATTRIBUTE_UPDATED: None,+ ATTRIBUTE_DELETED: None,CATEGORY_CREATED: ProductPermissions.MANAGE_PRODUCTS,CATEGORY_UPDATED: ProductPermissions.MANAGE_PRODUCTS,CATEGORY_DELETED: ProductPermissions.MANAGE_PRODUCTS,@@ -468,6 +481,9 @@ SUBSCRIBABLE_EVENTS = [WebhookEventAsyncType.APP_UPDATED,WebhookEventAsyncType.APP_DELETED,WebhookEventAsyncType.APP_STATUS_CHANGED,+ WebhookEventAsyncType.ATTRIBUTE_CREATED,+ WebhookEventAsyncType.ATTRIBUTE_UPDATED,+ WebhookEventAsyncType.ATTRIBUTE_DELETED,WebhookEventAsyncType.CATEGORY_CREATED,WebhookEventAsyncType.CATEGORY_UPDATED,WebhookEventAsyncType.CATEGORY_DELETED,