Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Adjust customer events generation (#18597)
Iga Karbowiak8ec5811aa3a8
diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py b/saleor/graphql/account/bulk_mutations/customer_bulk_update.pyindex 1b601f9d41..ac76dbe377 100644--- a/saleor/graphql/account/bulk_mutations/customer_bulk_update.py+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_update.py@@ -32,6 +32,7 @@ from ...core.validators import validate_one_of_args_is_in_mutationfrom ...meta.inputs import MetadataInputfrom ...payment.utils import deprecated_metadata_contains_empty_keyfrom ...plugins.dataloaders import get_app_promise, get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..i18n import I18nMixinfrom ..mutations.base import (BILLING_ADDRESS_FIELD,@@ -580,6 +581,8 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):def post_save_actions(cls, info, manager, instances, old_instances):customer_events = []app = get_app_promise(info.context).get()+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emissionstaff_user = info.context.userusers_with_name_or_email_updated = []webhooks_meta = get_webhooks_for_event(@@ -591,9 +594,6 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):for updated_instance, old_instance in zip(instances, old_instances, strict=False):- cls.call_event(- manager.customer_updated, updated_instance, webhooks=webhooks_updated- )new_email = updated_instance.emailnew_fullname = updated_instance.get_full_name()@@ -602,7 +602,10 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):has_new_email = old_instance.email != new_emailwas_activated = not old_instance.is_active and updated_instance.is_activewas_deactivated = old_instance.is_active and not updated_instance.is_active- metadata_update = old_instance.metadata != updated_instance.metadata+ metadata_update = (+ old_instance.metadata != updated_instance.metadata+ or old_instance.private_metadata != updated_instance.private_metadata+ )being_confirmed = (not old_instance.is_confirmed and updated_instance.is_confirmed)@@ -655,6 +658,36 @@ class CustomerBulkUpdate(BaseMutation, I18nMixin):))+ note_changed = old_instance.note != updated_instance.note+ language_code_changed = (+ old_instance.language_code != updated_instance.language_code+ )+ external_reference_changed = (+ old_instance.external_reference != updated_instance.external_reference+ )+ address_changed = (+ old_instance.default_billing_address_id+ != updated_instance.default_billing_address_id+ or old_instance.default_shipping_address_id+ != updated_instance.default_shipping_address_id+ )+ instance_modified = (+ has_new_name+ or has_new_email+ or was_activated+ or was_deactivated+ or being_confirmed+ or address_changed+ or note_changed+ or language_code_changed+ or external_reference_changed+ )+ if instance_modified or (metadata_update and use_legacy_webhooks_emission):+ cls.call_event(+ manager.customer_updated,+ updated_instance,+ webhooks=webhooks_updated,+ )if metadata_update:cls.call_event(manager.customer_metadata_updated,diff --git a/saleor/graphql/account/mutations/account/account_update.py b/saleor/graphql/account/mutations/account/account_update.pyindex 765d606ac9..c053f16152 100644--- a/saleor/graphql/account/mutations/account/account_update.py+++ b/saleor/graphql/account/mutations/account/account_update.py@@ -15,10 +15,12 @@ from ....core.types import AccountError, NonNullListfrom ....core.utils import WebhookEventInfofrom ....meta.inputs import MetadataInput, MetadataInputDescriptionfrom ....plugins.dataloaders import get_plugin_manager_promise+from ....site.dataloaders import get_site_promisefrom ...mixins import AppImpersonateMixinfrom ...types import AddressInput, Userfrom ..base import BaseCustomerCreatefrom .base import AccountBaseInput+from .utils import ACCOUNT_UPDATE_FIELDSclass AccountInput(AccountBaseInput):@@ -86,6 +88,7 @@ class AccountUpdate(AddressMetadataMixin, BaseCustomerCreate, AppImpersonateMixidescription="Optionally called when customer's metadata was updated.",),]+ instance_tracker_fields = list(ACCOUNT_UPDATE_FIELDS)@classmethoddef perform_mutation(cls, root, info: ResolveInfo, /, **data):@@ -104,11 +107,30 @@ class AccountUpdate(AddressMetadataMixin, BaseCustomerCreate, AppImpersonateMixicleaned_input,instance_tracker=None,):+ modified_instance_fields = set(instance_tracker.get_modified_fields())+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ meta_modified_fields = {"metadata"} & modified_instance_fieldsmanager = get_plugin_manager_promise(info.context).get()- cls.save_default_addresses(cleaned_input=cleaned_input, user_instance=instance)+ if changed_fields := cls.save_default_addresses(+ cleaned_input=cleaned_input, user_instance=instance+ ):+ modified_instance_fields.update(changed_fields)- instance.search_document = prepare_user_search_document_value(instance)- instance.save()+ non_metadata_modified_fields = modified_instance_fields - meta_modified_fields+ if non_metadata_modified_fields:+ instance.search_document = prepare_user_search_document_value(instance)+ modified_instance_fields.add("search_document")- cls.call_event(manager.customer_updated, instance)+ if modified_instance_fields:+ modified_instance_fields.add("updated_at")+ instance.save(update_fields=list(modified_instance_fields))++ if non_metadata_modified_fields or (+ use_legacy_webhooks_emission and meta_modified_fields+ ):+ cls.call_event(manager.customer_updated, instance)++ if meta_modified_fields:+ cls.call_event(manager.customer_metadata_updated, instance)diff --git a/saleor/graphql/account/mutations/account/utils.py b/saleor/graphql/account/mutations/account/utils.pyindex b067162609..06152dc9ef 100644--- a/saleor/graphql/account/mutations/account/utils.py+++ b/saleor/graphql/account/mutations/account/utils.py@@ -14,3 +14,11 @@ ADDRESS_UPDATE_FIELDS = {"street_address_2","validation_skipped",}+++ACCOUNT_UPDATE_FIELDS = {+ "metadata",+ "first_name",+ "last_name",+ "language_code",+}diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 89bf03bc5d..38da313c90 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -344,24 +344,24 @@ class BaseCustomerCreate(DeprecatedModelMutation, I18nMixin):@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):- if cleaned_input.get("metadata"):- manager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.customer_metadata_updated, instance)-if cleaned_input.get("first_name") or cleaned_input.get("last_name"):if user_gift_cards := get_user_gift_cards(instance):mark_gift_cards_search_index_as_dirty(user_gift_cards)@classmethod- def save_default_addresses(cls, *, cleaned_input: dict, user_instance: models.User):+ def save_default_addresses(+ cls, *, cleaned_input: dict, user_instance: models.User+ ) -> set[str]:default_shipping_address: models.Address | None = cleaned_input.get(SHIPPING_ADDRESS_FIELD)+ changed_fields = set()if default_shipping_address:default_shipping_address.save()user_instance.addresses.add(default_shipping_address)user_instance.default_shipping_address = default_shipping_address+ changed_fields.add("default_shipping_address")default_billing_address: models.Address | None = cleaned_input.get(BILLING_ADDRESS_FIELD@@ -371,6 +371,9 @@ class BaseCustomerCreate(DeprecatedModelMutation, I18nMixin):default_billing_address.save()user_instance.addresses.add(default_billing_address)user_instance.default_billing_address = default_billing_address+ changed_fields.add("default_billing_address")++ return changed_fieldsclass UserDeleteMixin:diff --git a/saleor/graphql/account/mutations/staff/customer_create.py b/saleor/graphql/account/mutations/staff/customer_create.pyindex 00b2c08c8c..de095c8a10 100644--- a/saleor/graphql/account/mutations/staff/customer_create.py+++ b/saleor/graphql/account/mutations/staff/customer_create.py@@ -118,9 +118,10 @@ class CustomerCreate(BaseCustomerCreate):instance.search_document = prepare_user_search_document_value(instance)instance.save()- cls.call_event(manager.customer_created, instance)account_events.customer_account_created_event(user=instance)+ cls.call_event(manager.customer_created, instance)+if redirect_url := cleaned_input.get("redirect_url"):cls._process_sending_password(redirect_url=redirect_url,@@ -129,6 +130,13 @@ class CustomerCreate(BaseCustomerCreate):plugins_manager=manager,)+ @classmethod+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):+ if cleaned_input.get("metadata") or cleaned_input.get("private_metadata"):+ manager = get_plugin_manager_promise(info.context).get()+ cls.call_event(manager.customer_metadata_updated, instance)+ super().post_save_action(info, instance, cleaned_input)+@classmethoddef _process_sending_password(cls,diff --git a/saleor/graphql/account/mutations/staff/customer_update.py b/saleor/graphql/account/mutations/staff/customer_update.pyindex 063ef7f3ff..d0eefde5aa 100644--- a/saleor/graphql/account/mutations/staff/customer_update.py+++ b/saleor/graphql/account/mutations/staff/customer_update.py@@ -1,4 +1,4 @@-from copy import copy+from typing import castimport graphenefrom django.db.models import QuerySet@@ -7,6 +7,7 @@ from .....account import events as account_eventsfrom .....account import modelsfrom .....account.search import prepare_user_search_document_valuefrom .....core.tracing import traced_atomic_transaction+from .....core.utils.update_mutation_manager import InstanceTrackerfrom .....giftcard.search import mark_gift_cards_search_index_as_dirtyfrom .....giftcard.utils import assign_user_gift_cards, get_user_gift_cardsfrom .....order.utils import match_orders_with_new_user@@ -21,7 +22,9 @@ from ....core.types import AccountErrorfrom ....core.utils import WebhookEventInfofrom ....meta.inputs import MetadataInputfrom ....plugins.dataloaders import get_plugin_manager_promise+from ....site.dataloaders import get_site_promisefrom ..base import BaseCustomerCreate, CustomerInput+from .utils import CUSTOMER_UPDATE_FIELDSclass CustomerUpdate(BaseCustomerCreate, ModelWithExtRefMutation):@@ -57,60 +60,74 @@ class CustomerUpdate(BaseCustomerCreate, ModelWithExtRefMutation):),]+ FIELDS_TO_TRACK = list(CUSTOMER_UPDATE_FIELDS)+@classmethoddef generate_events(- cls, info: ResolveInfo, old_instance: models.User, new_instance: models.User+ cls,+ info: ResolveInfo,+ instance: models.User,+ instance_tracker: InstanceTracker,+ modified_instance_fields: set,):# Retrieve the event base datastaff_user = info.context.userapp = get_app_promise(info.context).get()- new_email = new_instance.email- new_fullname = new_instance.get_full_name()# Compare the data- has_new_name = old_instance.get_full_name() != new_fullname- has_new_email = old_instance.email != new_email- was_activated = not old_instance.is_active and new_instance.is_active- was_deactivated = old_instance.is_active and not new_instance.is_active- being_confirmed = not old_instance.is_confirmed and new_instance.is_confirmed+ previous_active = instance_tracker.initial_instance_values.get("is_active")+ previous_confirmed = instance_tracker.initial_instance_values.get(+ "is_confirmed"+ )+ was_activated = not previous_active and instance.is_active+ was_deactivated = previous_active and not instance.is_active+ being_confirmed = not previous_confirmed and instance.is_confirmed- if has_new_email or being_confirmed:- assign_user_gift_cards(new_instance)- match_orders_with_new_user(new_instance)+ if "email" in modified_instance_fields or being_confirmed:+ assign_user_gift_cards(instance)+ match_orders_with_new_user(instance)# Generate the events accordingly- if has_new_email:+ if "email" in modified_instance_fields:account_events.assigned_email_to_a_customer_event(- staff_user=staff_user, app=app, new_email=new_email+ staff_user=staff_user, app=app, new_email=instance.email)- if has_new_name:+ if (+ "first_name" in modified_instance_fields+ or "last_name" in modified_instance_fields+ ):account_events.assigned_name_to_a_customer_event(- staff_user=staff_user, app=app, new_name=new_fullname+ staff_user=staff_user, app=app, new_name=instance.get_full_name())if was_activated:account_events.customer_account_activated_event(staff_user=info.context.user,app=app,- account_id=old_instance.id,+ account_id=instance.id,)if was_deactivated:account_events.customer_account_deactivated_event(staff_user=info.context.user,app=app,- account_id=old_instance.id,+ account_id=instance.id,)@classmethoddef update_gift_card_search_vector(cls,- old_instance: models.User,- new_instance: models.User,+ instance: models.User,+ instance_tracker: InstanceTracker,gift_cards: QuerySet,):- new_email = new_instance.email- new_fullname = new_instance.get_full_name()- has_new_name = old_instance.get_full_name() != new_fullname- has_new_email = old_instance.email != new_email+ has_new_name = (+ instance_tracker.initial_instance_values.get("first_name")+ != instance.first_name+ or instance_tracker.initial_instance_values.get("last_name")+ != instance.last_name+ )+ has_new_email = (+ instance_tracker.initial_instance_values.get("email") != instance.email+ )if has_new_email or has_new_name:mark_gift_cards_search_index_as_dirty(gift_cards)@@ -122,11 +139,14 @@ class CustomerUpdate(BaseCustomerCreate, ModelWithExtRefMutation):"""# Retrieve the data- original_instance = cls.get_instance(info, **data)+ instance = cls.get_instance(info, **data)+ instance = cast(models.User, instance)+ instance_tracker = InstanceTracker(instance, cls.FIELDS_TO_TRACK)data = data.get("input")+ gift_cards = get_user_gift_cards(instance)# Clean the input and generate a new instance from the new data- cleaned_input = cls.clean_input(info, original_instance, data)+ cleaned_input = cls.clean_input(info, instance, data)metadata_list: list[MetadataInput] = cleaned_input.pop("metadata", None)private_metadata_list: list[MetadataInput] = cleaned_input.pop("private_metadata", None@@ -139,42 +159,69 @@ class CustomerUpdate(BaseCustomerCreate, ModelWithExtRefMutation):private_metadata_list, error_field_name="private_metadata")- new_instance = cls.construct_instance(copy(original_instance), cleaned_input)+ instance = cls.construct_instance(instance, cleaned_input)cls.validate_and_update_metadata(- new_instance, metadata_collection, private_metadata_collection+ instance, metadata_collection, private_metadata_collection)# Save the new instance data- cls.clean_instance(info, new_instance)- cls.save(info, new_instance, cleaned_input)- cls._save_m2m(info, new_instance, cleaned_input)+ cls.clean_instance(info, instance)+ non_metadata_modified_fields, metadata_modified_fields = cls._save(+ info, instance, cleaned_input, instance_tracker+ )+ cls._save_m2m(info, instance, cleaned_input)- # Generate events by comparing the instances- cls.generate_events(info, original_instance, new_instance)+ cls.generate_events(+ info, instance, instance_tracker, non_metadata_modified_fields+ )- if metadata_list:+ if non_metadata_modified_fields or metadata_modified_fields:+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = (+ site.settings.use_legacy_update_webhook_emission+ )manager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.customer_metadata_updated, new_instance)+ if non_metadata_modified_fields or (+ metadata_modified_fields and use_legacy_webhooks_emission+ ):+ cls.call_event(manager.customer_updated, instance)- if gift_cards := get_user_gift_cards(new_instance):- cls.update_gift_card_search_vector(- original_instance, new_instance, gift_cards- )+ if metadata_modified_fields:+ cls.call_event(manager.customer_metadata_updated, instance)++ if gift_cards:+ cls.update_gift_card_search_vector(instance, instance_tracker, gift_cards)# Return the response- return cls.success_response(new_instance)+ return cls.success_response(instance)@classmethod@traced_atomic_transaction()- def save(cls, info: ResolveInfo, instance, cleaned_input, instance_tracker=None):- manager = get_plugin_manager_promise(info.context).get()-- cls.save_default_addresses(+ def _save(+ cls, info: ResolveInfo, instance, cleaned_input, instance_tracker+ ) -> tuple[set, set]:+ instance = cast(models.User, instance_tracker.instance)+ modified_instance_fields = set(instance_tracker.get_modified_fields())+ metadata_modified_fields = {+ "metadata",+ "private_metadata",+ } & modified_instance_fields++ if changed_fields := cls.save_default_addresses(cleaned_input=cleaned_input,user_instance=instance,+ ):+ modified_instance_fields.update(changed_fields)++ non_metadata_modified_fields = (+ set(modified_instance_fields) - metadata_modified_fields)+ if non_metadata_modified_fields:+ instance.search_document = prepare_user_search_document_value(instance)+ modified_instance_fields.add("search_document")- instance.search_document = prepare_user_search_document_value(instance)- instance.save()+ if modified_instance_fields:+ modified_instance_fields.add("updated_at")+ instance.save(update_fields=list(modified_instance_fields))- cls.call_event(manager.customer_updated, instance)+ return non_metadata_modified_fields, metadata_modified_fieldsdiff --git a/saleor/graphql/account/mutations/staff/utils.py b/saleor/graphql/account/mutations/staff/utils.pynew file mode 100644index 0000000000..f79890af6e--- /dev/null+++ b/saleor/graphql/account/mutations/staff/utils.py@@ -0,0 +1,11 @@+CUSTOMER_UPDATE_FIELDS = {+ "first_name",+ "last_name",+ "email",+ "is_active",+ "note",+ "external_reference",+ "is_confirmed",+ "metadata",+ "private_metadata",+}diff --git a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.pyindex dae4728433..bdb1cdcd36 100644--- a/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py+++ b/saleor/graphql/account/tests/bulk_mutations/test_customer_bulk_update.py@@ -1,6 +1,7 @@from unittest.mock import ANY, patchimport graphene+import pytestfrom .....account import modelsfrom .....account.error_codes import CustomerBulkUpdateErrorCode@@ -971,3 +972,182 @@ def test_customers_bulk_update_skip_address_validation(billing_address.refresh_from_db()assert billing_address.postal_code == wrong_postal_codeassert billing_address.validation_skipped is True+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+ ("field", "model_field"),+ [("metadata", "metadata"), ("privateMetadata", "private_metadata")],+)+def test_bulk_metadata_update_with_changed_legacy_webhook_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_users,+ permission_manage_users,+ site_settings,+ field,+ model_field,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ customer_1 = customer_users[0]+ customer_2 = customer_users[1]+ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)++ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ customers_input = [+ {"id": customer_1_id, "input": {field: metadata}},+ {"id": customer_2_id, "input": {field: metadata}},+ ]+ variables = {"customers": customers_input}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerBulkUpdate"]["results"][0]["errors"]+ assert not content["data"]["customerBulkUpdate"]["results"][1]["errors"]+ assert content["data"]["customerBulkUpdate"]["count"] == 2++ customer_1.refresh_from_db()+ customer_2.refresh_from_db()+ assert getattr(customer_1, model_field)[key] == value+ assert getattr(customer_2, model_field)[key] == value++ # Verify webhooks+ assert mocked_customer_updated.call_count == 2+ assert mocked_customer_metadata_updated.call_count == 2+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+ ("field", "model_field"),+ [("metadata", "metadata"), ("privateMetadata", "private_metadata")],+)+def test_bulk_metadata_update_with_changed_legacy_webhook_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_users,+ permission_manage_users,+ site_settings,+ field,+ model_field,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ customer_1 = customer_users[0]+ customer_2 = customer_users[1]+ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)++ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ customers_input = [+ {"id": customer_1_id, "input": {field: metadata}},+ {"id": customer_2_id, "input": {field: metadata}},+ ]+ variables = {"customers": customers_input}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerBulkUpdate"]["results"][0]["errors"]+ assert not content["data"]["customerBulkUpdate"]["results"][1]["errors"]+ assert content["data"]["customerBulkUpdate"]["count"] == 2++ customer_1.refresh_from_db()+ customer_2.refresh_from_db()+ assert getattr(customer_1, model_field)[key] == value+ assert getattr(customer_2, model_field)[key] == value++ # Verify webhooks+ mocked_customer_updated.assert_not_called()+ assert mocked_customer_metadata_updated.call_count == 2+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")[email protected]("use_legacy_update_webhook_emission", [True, False])+def test_bulk_metadata_and_customer_data_update_sends_both_webhooks(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_users,+ permission_manage_users,+ site_settings,+ use_legacy_update_webhook_emission,+):+ # given+ site_settings.use_legacy_update_webhook_emission = (+ use_legacy_update_webhook_emission+ )+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ customer_1 = customer_users[0]+ customer_2 = customer_users[1]+ customer_1_id = graphene.Node.to_global_id("User", customer_1.pk)+ customer_2_id = graphene.Node.to_global_id("User", customer_2.pk)++ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ customers_input = [+ {+ "id": customer_1_id,+ "input": {+ "firstName": "UpdatedName1",+ "metadata": metadata,+ "privateMetadata": metadata,+ },+ },+ {+ "id": customer_2_id,+ "input": {+ "firstName": "UpdatedName2",+ "metadata": metadata,+ "privateMetadata": metadata,+ },+ },+ ]+ variables = {"customers": customers_input}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerBulkUpdate"]["results"][0]["errors"]+ assert not content["data"]["customerBulkUpdate"]["results"][1]["errors"]+ assert content["data"]["customerBulkUpdate"]["count"] == 2++ customer_1.refresh_from_db()+ customer_2.refresh_from_db()+ assert customer_1.first_name == "UpdatedName1"+ assert customer_2.first_name == "UpdatedName2"+ assert customer_1.metadata[key] == value+ assert customer_2.metadata[key] == value++ # Verify both webhooks were sent+ assert mocked_customer_updated.call_count == 2+ assert mocked_customer_metadata_updated.call_count == 2diff --git a/saleor/graphql/account/tests/mutations/account/test_account_update.py b/saleor/graphql/account/tests/mutations/account/test_account_update.pyindex f300cc45b2..1bc63873bc 100644--- a/saleor/graphql/account/tests/mutations/account/test_account_update.py+++ b/saleor/graphql/account/tests/mutations/account/test_account_update.py@@ -1,6 +1,7 @@from unittest.mock import patchimport graphene+import pytestfrom ......account.error_codes import AccountErrorCodefrom ......account.models import User@@ -10,23 +11,11 @@ from .....tests.utils import assert_no_permission, get_graphql_contentACCOUNT_UPDATE_QUERY = """mutation accountUpdate(- $billing: AddressInput- $shipping: AddressInput- $firstName: String,- $lastName: String- $languageCode: LanguageCodeEnum- $metadata: [MetadataInput!]+ $input: AccountInput!$customerId: ID) {accountUpdate(- input: {- defaultBillingAddress: $billing,- defaultShippingAddress: $shipping,- firstName: $firstName,- lastName: $lastName,- languageCode: $languageCode,- metadata: $metadata,- },+ input: $input,customerId: $customerId) {errors {@@ -71,7 +60,7 @@ def test_logged_customer_updates_language_code(user_api_client):language_code = "PL"user = user_api_client.userassert user.language_code != language_code- variables = {"languageCode": language_code}+ variables = {"input": {"languageCode": language_code}}response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)content = get_graphql_content(response)@@ -91,7 +80,7 @@ def test_logged_customer_update_names(user_api_client):assert user.first_name != first_nameassert user.last_name != last_name- variables = {"firstName": first_name, "lastName": last_name}+ variables = {"input": {"firstName": first_name, "lastName": last_name}}response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)content = get_graphql_content(response)data = content["data"]["accountUpdate"]@@ -108,6 +97,7 @@ def test_logged_customer_update_addresses(user_api_client, graphql_address_data)user = user_api_client.usernew_first_name = graphql_address_data["firstName"]metadata = graphql_address_data["metadata"]+ updated_at = user.updated_atassert user.default_billing_addressassert user.default_shipping_addressassert user.default_billing_address.first_name != new_first_name@@ -115,7 +105,12 @@ def test_logged_customer_update_addresses(user_api_client, graphql_address_data)query = ACCOUNT_UPDATE_QUERYmutation_name = "accountUpdate"- variables = {"billing": graphql_address_data, "shipping": graphql_address_data}+ variables = {+ "input": {+ "defaultBillingAddress": graphql_address_data,+ "defaultShippingAddress": graphql_address_data,+ }+ }response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)data = content["data"][mutation_name]@@ -141,6 +136,8 @@ def test_logged_customer_update_addresses(user_api_client, graphql_address_data)assert user.default_billing_address.validation_skipped is Falseassert user.default_shipping_address.validation_skipped is False+ assert user.updated_at > updated_at+def test_logged_customer_update_addresses_invalid_shipping_address(user_api_client, graphql_address_data@@ -150,7 +147,12 @@ def test_logged_customer_update_addresses_invalid_shipping_address(query = ACCOUNT_UPDATE_QUERYmutation_name = "accountUpdate"- variables = {"billing": graphql_address_data, "shipping": shipping_address}+ variables = {+ "input": {+ "defaultBillingAddress": graphql_address_data,+ "defaultShippingAddress": shipping_address,+ }+ }response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)data = content["data"][mutation_name]@@ -169,7 +171,12 @@ def test_logged_customer_update_addresses_invalid_billing_address(query = ACCOUNT_UPDATE_QUERYmutation_name = "accountUpdate"- variables = {"billing": billing_address, "shipping": graphql_address_data}+ variables = {+ "input": {+ "defaultBillingAddress": billing_address,+ "defaultShippingAddress": graphql_address_data,+ }+ }response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)data = content["data"][mutation_name]@@ -182,7 +189,7 @@ def test_logged_customer_update_addresses_invalid_billing_address(def test_logged_customer_update_anonymous_user(api_client):query = ACCOUNT_UPDATE_QUERY- response = api_client.post_graphql(query, {})+ response = api_client.post_graphql(query, {"input": {}})assert_no_permission(response)@@ -192,7 +199,7 @@ def test_logged_customer_updates_metadata():# givenmetadata = {"key": "test key", "value": "test value"}- variables = {"metadata": [metadata]}+ variables = {"input": {"metadata": [metadata]}}# whenresponse = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)@@ -219,7 +226,7 @@ def test_logged_customer_update_names_trigger_gift_card_search_vector_update(card.refresh_from_db()assert card.search_index_dirty is False- variables = {"firstName": first_name, "lastName": last_name}+ variables = {"input": {"firstName": first_name, "lastName": last_name}}# whenresponse = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)@@ -242,7 +249,12 @@ def test_logged_customer_update_address_skip_validation(address_data = graphql_address_data_skipped_validationinvalid_postal_code = "invalid_postal_code"address_data["postalCode"] = invalid_postal_code- variables = {"shipping": address_data, "billing": address_data}+ variables = {+ "input": {+ "defaultShippingAddress": address_data,+ "defaultBillingAddress": address_data,+ }+ }# whenresponse = user_api_client.post_graphql(query, variables)@@ -261,7 +273,10 @@ def test_account_update_by_app(user = customer_useruser_id = graphene.Node.to_global_id("User", user.pk)assert user.default_billing_address.city != new_city- variables = {"billing": address_input, "customerId": user_id}+ variables = {+ "input": {"defaultBillingAddress": address_input},+ "customerId": user_id,+ }# whenresponse = app_api_client.post_graphql(@@ -282,7 +297,10 @@ def test_account_update_by_app_no_permissions():# givencustomer_id = graphene.Node.to_global_id("User", customer_user.pk)- variables = {"billing": graphql_address_data, "customerId": customer_id}+ variables = {+ "input": {"defaultBillingAddress": graphql_address_data},+ "customerId": customer_id,+ }# whenresponse = app_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)@@ -296,7 +314,10 @@ def test_account_update_by_user_with_customer_id():# givencustomer_id = graphene.Node.to_global_id("User", customer_user.pk)- variables = {"billing": graphql_address_data, "customerId": customer_id}+ variables = {+ "input": {"defaultBillingAddress": graphql_address_data},+ "customerId": customer_id,+ }# whenresponse = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)@@ -316,7 +337,10 @@ def test_account_address_create_by_app_invalid_customer_id():# givencustomer_id = graphene.Node.to_global_id("Address", customer_user.pk)- variables = {"addressInput": graphql_address_data, "customerId": customer_id}+ variables = {+ "input": {"defaultBillingAddress": graphql_address_data},+ "customerId": customer_id,+ }# whenresponse = app_api_client.post_graphql(@@ -339,7 +363,7 @@ def test_account_address_create_by_app_no_customer_id(app_api_client, graphql_address_data, permission_impersonate_user):# given- variables = {"billing": graphql_address_data}+ variables = {"input": {"defaultBillingAddress": graphql_address_data}}# whenresponse = app_api_client.post_graphql(@@ -371,8 +395,10 @@ def test_account_update_address_by_app_skip_validation(invalid_postal_code = "invalid_postal_code"address_data["postalCode"] = invalid_postal_codevariables = {- "shipping": address_data,- "billing": address_data,+ "input": {+ "defaultShippingAddress": address_data,+ "defaultBillingAddress": address_data,+ },"customerId": customer_id,}@@ -406,8 +432,10 @@ def test_account_update_address_by_app_skip_validation_no_permissions(invalid_postal_code = "invalid_postal_code"address_data["postalCode"] = invalid_postal_codevariables = {- "shipping": address_data,- "billing": address_data,+ "input": {+ "defaultShippingAddress": address_data,+ "defaultBillingAddress": address_data,+ },"customerId": customer_id,}@@ -416,3 +444,142 @@ def test_account_update_address_by_app_skip_validation_no_permissions(# thenassert_no_permission(response)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")[email protected]("use_legacy_update_webhook_emission", [True, False])+def test_account_update_sends_customer_updated_webhook(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ user_api_client,+ site_settings,+ use_legacy_update_webhook_emission,+):+ # given+ site_settings.use_legacy_update_webhook_emission = (+ use_legacy_update_webhook_emission+ )+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user = user_api_client.user+ variables = {"input": {"firstName": "UpdatedName"}}++ # when+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["accountUpdate"]["errors"]+ user.refresh_from_db()+ assert user.first_name == "UpdatedName"++ # Verify customer_updated webhook was sent+ mocked_customer_updated.assert_called_once_with(user)+ mocked_customer_metadata_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_account_metadata_update_with_legacy_webhook_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ user_api_client,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user = user_api_client.user+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {"input": {"metadata": metadata}}++ # when+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["accountUpdate"]["errors"]+ user.refresh_from_db()+ assert user.metadata[key] == value++ # Verify webhooks+ mocked_customer_updated.assert_called_once_with(user)+ mocked_customer_metadata_updated.assert_called_once_with(user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_account_metadata_update_with_legacy_webhook_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ user_api_client,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user = user_api_client.user+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {"input": {"metadata": metadata}}++ # when+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["accountUpdate"]["errors"]+ user.refresh_from_db()+ assert user.metadata[key] == value++ # Verify webhooks+ mocked_customer_updated.assert_not_called()+ mocked_customer_metadata_updated.assert_called_once_with(user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")[email protected]("use_legacy_update_webhook_emission", [True, False])+def test_account_metadata_and_data_update_sends_both_webhooks(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ user_api_client,+ site_settings,+ use_legacy_update_webhook_emission,+):+ # given+ site_settings.use_legacy_update_webhook_emission = (+ use_legacy_update_webhook_emission+ )+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user = user_api_client.user+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {+ "input": {+ "firstName": "UpdatedName",+ "metadata": metadata,+ }+ }++ # when+ response = user_api_client.post_graphql(ACCOUNT_UPDATE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ assert not content["data"]["accountUpdate"]["errors"]+ user.refresh_from_db()+ assert user.first_name == "UpdatedName"+ assert user.metadata[key] == value++ # Verify both webhooks were sent+ mocked_customer_updated.assert_called_once_with(user)+ mocked_customer_metadata_updated.assert_called_once_with(user)diff --git a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py b/saleor/graphql/account/tests/mutations/staff/test_customer_update.pyindex bca9e5d71b..852e4d7ed0 100644--- a/saleor/graphql/account/tests/mutations/staff/test_customer_update.py+++ b/saleor/graphql/account/tests/mutations/staff/test_customer_update.py@@ -1,6 +1,7 @@from unittest.mock import patchimport graphene+import pytestfrom ......account import events as account_eventsfrom ......account.error_codes import AccountErrorCode@@ -79,6 +80,7 @@ def test_customer_update(assert customer_user.default_shipping_addressbilling_address_pk = customer_user.default_billing_address.pkshipping_address_pk = customer_user.default_shipping_address.pk+ updated_at = customer_user.updated_atuser_id = graphene.Node.to_global_id("User", customer_user.id)first_name = "new_first_name"@@ -161,6 +163,8 @@ def test_customer_update(assert deactivated_event.user.pk == staff_user.pkassert deactivated_event.parameters == {"account_id": customer_user.id}+ assert customer_user.updated_at > updated_at+customer_user.refresh_from_db()assert (generate_address_search_document_value(billing_address)@@ -173,6 +177,184 @@ def test_customer_update(mocked_customer_metadata_updated.assert_called_once_with(customer_user)+@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")[email protected]("use_legacy_update_webhook_emission", [True, False])+def test_customer_data_update_sends_customer_updated_webhook(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_user,+ permission_manage_users,+ site_settings,+ use_legacy_update_webhook_emission,+):+ # given+ site_settings.use_legacy_update_webhook_emission = (+ use_legacy_update_webhook_emission+ )+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ variables = {+ "id": user_id,+ "input": {"firstName": "UpdatedName"},+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert customer_user.first_name == "UpdatedName"++ # Verify customer_updated webhook was sent+ mocked_customer_updated.assert_called_once_with(customer_user)+ mocked_customer_metadata_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+ ("field", "model_field"),+ [("metadata", "metadata"), ("privateMetadata", "private_metadata")],+)+def test_metadata_update_with_changed_legacy_webhook_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_user,+ permission_manage_users,+ site_settings,+ field,+ model_field,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {+ "id": user_id,+ "input": {field: metadata},+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert getattr(customer_user, model_field)[key] == value++ # Verify webhooks+ mocked_customer_updated.assert_called_once_with(customer_user)+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+ ("field", "model_field"),+ [("metadata", "metadata"), ("privateMetadata", "private_metadata")],+)+def test_metadata_update_with_changed_legacy_webhook_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_user,+ permission_manage_users,+ site_settings,+ field,+ model_field,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {+ "id": user_id,+ "input": {field: metadata},+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert getattr(customer_user, model_field)[key] == value++ # Verify webhooks+ mocked_customer_updated.assert_not_called()+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")[email protected]("use_legacy_update_webhook_emission", [True, False])+def test_metadata_and_customer_data_update_sends_both_webhooks(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ customer_user,+ permission_manage_users,+ site_settings,+ use_legacy_update_webhook_emission,+):+ # given+ site_settings.use_legacy_update_webhook_emission = (+ use_legacy_update_webhook_emission+ )+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ key = "test_key"+ value = "test_value"+ metadata = [{"key": key, "value": value}]+ variables = {+ "id": user_id,+ "input": {+ "firstName": "UpdatedName",+ "metadata": metadata,+ "privateMetadata": metadata,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["customerUpdate"]["errors"]+ customer_user.refresh_from_db()+ assert customer_user.first_name == "UpdatedName"+ assert customer_user.metadata[key] == value++ # Verify both webhooks were sent+ mocked_customer_updated.assert_called_once_with(customer_user)+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)++UPDATE_CUSTOMER_BY_EXTERNAL_REFERENCE = """mutation UpdateCustomer($id: ID, $externalReference: String, $input: CustomerInput!diff --git a/saleor/graphql/channel/mutations/channel_update.py b/saleor/graphql/channel/mutations/channel_update.pyindex 26bc43405d..ab035861cc 100644--- a/saleor/graphql/channel/mutations/channel_update.py+++ b/saleor/graphql/channel/mutations/channel_update.py@@ -1,3 +1,5 @@+from typing import cast+import graphenefrom django.core.exceptions import ValidationErrorfrom django.utils.text import slugify@@ -5,6 +7,7 @@ from django.utils.text import slugifyfrom ....channel import modelsfrom ....channel.error_codes import ChannelErrorCodefrom ....core.tracing import traced_atomic_transaction+from ....core.utils.update_mutation_manager import InstanceTrackerfrom ....discount.tasks import (decrease_voucher_code_usage_of_draft_orders,disconnect_voucher_codes_from_draft_orders,@@ -25,12 +28,15 @@ from ...core.doc_category import DOC_CATEGORY_CHANNELSfrom ...core.mutations import DeprecatedModelMutationfrom ...core.types import ChannelError, NonNullListfrom ...core.utils import WebhookEventInfo+from ...meta.inputs import MetadataInputfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ...utils.validators import check_for_duplicatesfrom ..types import Channelfrom ..utils import delete_invalid_warehouse_to_shipping_zone_relationsfrom .channel_create import ChannelInputfrom .utils import (+ CHANNEL_UPDATE_FIELDS,clean_input_checkout_settings,clean_input_order_settings,clean_input_payment_settings,@@ -103,6 +109,44 @@ class ChannelUpdate(DeprecatedModelMutation):support_meta_field = Truesupport_private_meta_field = True+ FIELDS_TO_TRACK = list(CHANNEL_UPDATE_FIELDS)++ @classmethod+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):+ instance_tracker = None+ instance = cls.get_instance(info, **data)+ instance_tracker = InstanceTracker(instance, cls.FIELDS_TO_TRACK)++ data = data.get("input")+ cleaned_input = cls.clean_input(info, instance, data)++ metadata_list: list[MetadataInput] = cleaned_input.pop("metadata", None)+ private_metadata_list: list[MetadataInput] = cleaned_input.pop(+ "private_metadata", None+ )++ metadata_collection = cls.create_metadata_from_graphql_input(+ metadata_list, error_field_name="metadata"+ )+ private_metadata_collection = cls.create_metadata_from_graphql_input(+ private_metadata_list, error_field_name="private_metadata"+ )++ instance = cls.construct_instance(instance, cleaned_input)++ cls.validate_and_update_metadata(+ instance, metadata_collection, private_metadata_collection+ )+ cls.clean_instance(info, instance)+ instance_modified, metadata_modified = cls._save(instance, instance_tracker)+ m2m_modified = cls._save_m2m(info, instance, cleaned_input)++ cls.emit_events(+ info, instance, instance_modified or m2m_modified, metadata_modified+ )+ cls._update_voucher_usage(cleaned_input, instance)+ return cls.success_response(instance)+@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):errors = {}@@ -172,11 +216,29 @@ class ChannelUpdate(DeprecatedModelMutation):)@classmethod- def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data):+ def _save(cls, instance, instance_tracker) -> tuple[bool, bool]:+ instance = cast(models.Channel, instance)+ modified_instance_fields = set(instance_tracker.get_modified_fields())+ metadata_modified = (+ "metadata" in modified_instance_fields+ or "private_metadata" in modified_instance_fields+ )+ modified_instance_fields = set(modified_instance_fields) - {+ "metadata",+ "private_metadata",+ }++ if modified_instance_fields or metadata_modified:+ instance.save()++ return bool(modified_instance_fields), metadata_modified++ @classmethod+ def _save_m2m(cls, info: ResolveInfo, instance, cleaned_data) -> bool:+ modified = Falsewith traced_atomic_transaction():- super()._save_m2m(info, instance, cleaned_data)- cls._update_shipping_zones(instance, cleaned_data)- cls._update_warehouses(instance, cleaned_data)+ modified |= cls._update_shipping_zones(instance, cleaned_data)+ modified |= cls._update_warehouses(instance, cleaned_data)if ("remove_shipping_zones" in cleaned_dataor "remove_warehouses" in cleaned_data@@ -192,14 +254,18 @@ class ChannelUpdate(DeprecatedModelMutation):delete_invalid_warehouse_to_shipping_zone_relations(instance, warehouse_ids, shipping_zone_ids)+ return modified@classmethoddef _update_shipping_zones(cls, instance, cleaned_data):+ modified = Falseadd_shipping_zones = cleaned_data.get("add_shipping_zones")if add_shipping_zones:+ modified = Trueinstance.shipping_zones.add(*add_shipping_zones)remove_shipping_zones = cleaned_data.get("remove_shipping_zones")if remove_shipping_zones:+ modified = Trueinstance.shipping_zones.remove(*remove_shipping_zones)shipping_channel_listings = instance.shipping_method_listings.filter(shipping_method__shipping_zone__in=remove_shipping_zones@@ -211,15 +277,20 @@ class ChannelUpdate(DeprecatedModelMutation):drop_invalid_shipping_methods_relations_for_given_channels.delay(shipping_method_ids, [instance.id])+ return modified@classmethod- def _update_warehouses(cls, instance, cleaned_data):+ def _update_warehouses(cls, instance, cleaned_data) -> bool:+ modified = Falseadd_warehouses = cleaned_data.get("add_warehouses")if add_warehouses:instance.warehouses.add(*add_warehouses)+ modified = Trueremove_warehouses = cleaned_data.get("remove_warehouses")if remove_warehouses:instance.warehouses.remove(*remove_warehouses)+ modified = True+ return modified@classmethoddef _update_voucher_usage(cls, cleaned_input, instance):@@ -238,9 +309,13 @@ class ChannelUpdate(DeprecatedModelMutation):disconnect_voucher_codes_from_draft_orders(instance.id)@classmethod- def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):+ def emit_events(+ cls, info: ResolveInfo, instance, instance_modified, metadata_modified+ ):manager = get_plugin_manager_promise(info.context).get()- cls.call_event(manager.channel_updated, instance)- if cleaned_input.get("metadata"):+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ if instance_modified or (metadata_modified and use_legacy_webhooks_emission):+ cls.call_event(manager.channel_updated, instance)+ if metadata_modified:cls.call_event(manager.channel_metadata_updated, instance)- cls._update_voucher_usage(cleaned_input, instance)diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.pyindex 7aa2def45f..01f9822751 100644--- a/saleor/graphql/channel/mutations/utils.py+++ b/saleor/graphql/channel/mutations/utils.py@@ -7,6 +7,34 @@ from django.utils import timezonefrom ....channel.models import Channelfrom ...core.enums import ChannelErrorCode+CHANNEL_UPDATE_FIELDS = [+ "name",+ "slug",+ "default_country",+ "is_active",+ "allocation_strategy",+ "automatically_confirm_all_new_orders",+ "automatically_fulfill_non_shippable_gift_card",+ "expire_orders_after",+ "delete_expired_orders_after",+ "order_mark_as_paid_strategy",+ "allow_unpaid_orders",+ "include_draft_order_in_voucher_usage",+ "draft_order_line_price_freeze_period",+ "use_legacy_line_discount_propagation_for_order",+ "use_legacy_error_flow_for_checkout",+ "automatically_complete_fully_paid_checkouts",+ "automatic_completion_delay",+ "automatic_completion_cut_off_date",+ "default_transaction_flow_strategy",+ "release_funds_for_expired_checkouts",+ "checkout_ttl_before_releasing_funds",+ "checkout_release_funds_cut_off_date",+ "allow_legacy_gift_card_use",+ "metadata",+ "private_metadata",+]+DELETE_EXPIRED_ORDERS_MAX_DAYS = 120diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.pyindex e8a85659af..1a0a7b8f7c 100644--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py@@ -65,7 +65,11 @@ CHANNEL_UPDATE_MUTATION = """"""+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_as_staff_user(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -123,10 +127,18 @@ def test_channel_update_mutation_as_staff_user(assert channel_data["orderSettings"]["expireOrdersAfter"] == 10assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is Trueassert channel_data["orderSettings"]["allowUnpaidOrders"] is True+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_as_app(- permission_manage_channels, app_api_client, channel_USD+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ app_api_client,+ channel_USD,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -150,6 +162,8 @@ def test_channel_update_mutation_as_app(assert channel_data["name"] == channel_USD.name == nameassert channel_data["slug"] == channel_USD.slug == slugassert channel_data["currencyCode"] == channel_USD.currency_code == "USD"+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()def test_channel_update_mutation_as_customer(user_api_client, channel_USD):@@ -233,8 +247,14 @@ def test_channel_update_mutation_with_duplicated_slug(assert error["code"] == ChannelErrorCode.UNIQUE.name+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_only_name(- permission_manage_channels, staff_api_client, channel_USD+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ staff_api_client,+ channel_USD,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -258,10 +278,18 @@ def test_channel_update_mutation_only_name(assert channel_data["name"] == channel_USD.name == nameassert channel_data["slug"] == channel_USD.slug == slugassert channel_data["currencyCode"] == channel_USD.currency_code == "USD"+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_only_slug(- permission_manage_channels, staff_api_client, channel_USD+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ staff_api_client,+ channel_USD,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -285,10 +313,19 @@ def test_channel_update_mutation_only_slug(assert channel_data["name"] == channel_USD.name == nameassert channel_data["slug"] == channel_USD.slug == slugassert channel_data["currencyCode"] == channel_USD.currency_code == "USD"+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_add_shipping_zone(- permission_manage_channels, staff_api_client, channel_USD, shipping_zone+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ shipping_zone,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -319,14 +356,20 @@ def test_channel_update_mutation_add_shipping_zone(assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"actual_shipping_zone = channel_USD.shipping_zones.first()assert actual_shipping_zone == shipping_zone+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")@patch("saleor.graphql.channel.mutations.channel_update.""drop_invalid_shipping_methods_relations_for_given_channels.delay")def test_channel_update_mutation_remove_shipping_zone(mocked_drop_invalid_shipping_methods_relations,+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -392,6 +435,9 @@ def test_channel_update_mutation_remove_shipping_zone(for zone in shipping_zones[1:]:assert zone.warehouses.count() == len(warehouses)+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+def test_channel_update_mutation_add_and_remove_shipping_zone(permission_manage_channels,@@ -553,8 +599,15 @@ def test_channel_update_mutation_trigger_webhook()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_add_warehouse(- permission_manage_channels, staff_api_client, channel_USD, warehouse+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ staff_api_client,+ channel_USD,+ warehouse,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -585,11 +638,17 @@ def test_channel_update_mutation_add_warehouse(assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"assert len(channel_data["warehouses"]) == 1assert channel_data["warehouses"][0]["slug"] == warehouse.slug+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_remove_warehouse(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -664,8 +723,15 @@ def test_channel_update_mutation_remove_warehouse(# without JPY channelassert warehouses[1] not in shipping_zones[1].warehouses.all()+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()++@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_mutation_add_and_remove_warehouse(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -709,6 +775,9 @@ def test_channel_update_mutation_add_and_remove_warehouse(warehouse_data["slug"] for warehouse_data in channel_data["warehouses"]} == {warehouse.slug for warehouse in warehouses[1:] + [warehouse]}+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+def test_channel_update_mutation_duplicated_warehouses(permission_manage_channels,@@ -817,7 +886,11 @@ def test_channel_update_mutation_negative_expire_orders(assert error["code"] == ChannelErrorCode.INVALID.name+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_order_settings_manage_orders(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_orders,staff_api_client,channel_USD,@@ -855,6 +928,8 @@ def test_channel_update_order_settings_manage_orders(is False)assert channel_data["orderSettings"]["allowUnpaidOrders"] is False+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()def test_channel_update_order_settings_empty_order_settings(@@ -1310,9 +1385,15 @@ CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """"""+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")@freeze_time("2022-05-12 12:00:00")def test_channel_update_channel_settings(- permission_manage_channels, staff_api_client, channel_USD+ channel_updated_mock,+ channel_metadata_updated_mock,+ permission_manage_channels,+ staff_api_client,+ channel_USD,):# givenchannel_id = graphene.Node.to_global_id("Channel", channel_USD.id)@@ -1363,10 +1444,16 @@ def test_channel_update_channel_settings()assert channel_USD.automatic_completion_delay == default_delayassert channel_USD.automatic_completion_cut_off_date == timezone.now()+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()@freeze_time("2022-05-12 12:00:00")+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_set_automatic_checkout_completion(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -1409,6 +1496,9 @@ def test_channel_update_set_automatic_checkout_completion(assert channel_USD.automatic_completion_delay == delayassert channel_USD.automatic_completion_cut_off_date == timezone.now()+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+def test_channel_update_set_automatic_checkout_completion_change_to_false(permission_manage_channels,@@ -2019,7 +2109,11 @@ CHANNEL_UPDATE_MUTATION_WITH_PAYMENT_SETTINGS = """"""+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_default_transaction_flow_strategy(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -2058,9 +2152,15 @@ def test_channel_update_default_transaction_flow_strategy(channel_USD.default_transaction_flow_strategy== TransactionFlowStrategyEnum.AUTHORIZATION.value)+ channel_updated_mock.assert_called_once()+ channel_metadata_updated_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_updated")def test_channel_update_checkout_release_settings(+ channel_updated_mock,+ channel_metadata_updated_mock,permission_manage_channels,staff_api_client,channel_USD,@@ -2108,6 +2208,8 @@ def test_channel_update_checkout_release_settings(hours=ttl_before_releasing_funds)assert channel_USD.checkout_release_funds_cut_off_date == date+ channel_metadata_updated_mock.assert_not_called()+ channel_updated_mock.assert_called_once()def test_channel_create_set_incorect_checkout_ttl_before_releasing_funds(@@ -2270,3 +2372,45 @@ def test_channel_update_allow_legacy_gift_card_use(== allow_legacy_gift_card_use)assert channel_USD.allow_legacy_gift_card_use == allow_legacy_gift_card_use++[email protected]("meta_field", ["metadata", "privateMetadata"])+@patch("saleor.plugins.manager.PluginsManager.channel_updated")+@patch("saleor.plugins.manager.PluginsManager.channel_metadata_updated")+def test_channel_update_with_legacy_webhook_emission_off(+ channel_metadata_updated_mock,+ channel_updated_mock,+ meta_field,+ staff_api_client,+ channel_USD,+ permission_manage_channels,+ site_settings,+):+ # Given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ metadata_key = "key"+ metadata_value = "value"++ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)+ variables = {+ "id": channel_id,+ "input": {meta_field: [{"key": metadata_key, "value": metadata_value}]},+ }++ # When+ response = staff_api_client.post_graphql(+ CHANNEL_UPDATE_MUTATION,+ variables=variables,+ permissions=[permission_manage_channels],+ )+ channel_USD.refresh_from_db()+ content = get_graphql_content(response)+ data = content["data"]["channelUpdate"]++ # Then+ assert not data["errors"]++ channel_updated_mock.assert_not_called()+ channel_metadata_updated_mock.assert_called_once()diff --git a/saleor/graphql/meta/extra_methods.py b/saleor/graphql/meta/extra_methods.pyindex f7f1d43c19..b4dc40c3a7 100644--- a/saleor/graphql/meta/extra_methods.py+++ b/saleor/graphql/meta/extra_methods.py@@ -3,17 +3,21 @@ from ...order.actions import call_order_eventfrom ...webhook.event_types import WebhookEventAsyncTypefrom ..core import ResolveInfofrom ..plugins.dataloaders import get_plugin_manager_promise+from ..site.dataloaders import get_site_promisedef extra_checkout_actions(instance, info: ResolveInfo, **data):manager = get_plugin_manager_promise(info.context).get()-+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ events = [+ WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,+ ]+ if use_legacy_webhooks_emission:+ events.append(WebhookEventAsyncType.CHECKOUT_UPDATED)call_checkout_events(manager=manager,- event_names=[- WebhookEventAsyncType.CHECKOUT_UPDATED,- WebhookEventAsyncType.CHECKOUT_METADATA_UPDATED,- ],+ event_names=events,checkout=instance,)@@ -49,13 +53,19 @@ def extra_order_actions(instance, info: ResolveInfo, **data):def extra_product_actions(instance, info: ResolveInfo, **data):manager = get_plugin_manager_promise(info.context).get()- manager.product_updated(instance)+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ if use_legacy_webhooks_emission:+ manager.product_updated(instance)manager.product_metadata_updated(instance)def extra_variant_actions(instance, info: ResolveInfo, **data):manager = get_plugin_manager_promise(info.context).get()- manager.product_variant_updated(instance)+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ if use_legacy_webhooks_emission:+ manager.product_variant_updated(instance)manager.product_variant_metadata_updated(instance)@@ -71,7 +81,10 @@ def extra_transaction_item_actions(instance, info: ResolveInfo, **data):def extra_user_actions(instance, info: ResolveInfo, **data):manager = get_plugin_manager_promise(info.context).get()- manager.customer_updated(instance)+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emission+ if use_legacy_webhooks_emission:+ manager.customer_updated(instance)manager.customer_metadata_updated(instance)diff --git a/saleor/graphql/meta/tests/mutations/test_account.py b/saleor/graphql/meta/tests/mutations/test_account.pyindex d97ec9af90..166bbb67fa 100644--- a/saleor/graphql/meta/tests/mutations/test_account.py+++ b/saleor/graphql/meta/tests/mutations/test_account.py@@ -1,3 +1,5 @@+from unittest.mock import patch+import grapheneimport pytest@@ -579,6 +581,208 @@ def test_delete_public_metadata_for_myself_as_staff(staff_api_client):assert staff.updated_at > old_updated_at+@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_update_metadata_for_customer_with_use_legacy_update_webhook_emission_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_users,+ customer_id,+ "User",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ customer_user,+ customer_id,+ value="UpdatedValue",+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_update_metadata_for_customer_with_use_legacy_update_webhook_emission_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_users,+ customer_id,+ "User",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ customer_user,+ customer_id,+ value="UpdatedValue",+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_update_private_metadata_for_customer_use_legacy_update_webhook_emission_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_users,+ customer_id,+ "User",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ customer_user,+ customer_id,+ value="UpdatedPrivateValue",+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_update_private_metadata_for_customer_use_legacy_update_webhook_emission_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_users,+ customer_id,+ "User",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ customer_user,+ customer_id,+ value="UpdatedPrivateValue",+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_delete_metadata_for_customer_use_legacy_update_webhook_emission_on(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ customer_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ customer_user.save(update_fields=["metadata"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_users, customer_id, "User"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], customer_user, customer_id+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_called_once_with(customer_user)+++@patch("saleor.plugins.manager.PluginsManager.customer_updated")+@patch("saleor.plugins.manager.PluginsManager.customer_metadata_updated")+def test_delete_metadata_for_customer_use_legacy_update_webhook_emission_off(+ mocked_customer_metadata_updated,+ mocked_customer_updated,+ staff_api_client,+ permission_manage_users,+ customer_user,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ customer_user.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ customer_user.save(update_fields=["metadata"])+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_users, customer_id, "User"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], customer_user, customer_id+ )+ mocked_customer_metadata_updated.assert_called_once_with(customer_user)+ mocked_customer_updated.assert_not_called()++def test_update_public_metadata_for_customer_address_by_logged_user(user_api_client, address):diff --git a/saleor/graphql/meta/tests/mutations/test_checkout.py b/saleor/graphql/meta/tests/mutations/test_checkout.pyindex a931898f55..0064039ea0 100644--- a/saleor/graphql/meta/tests/mutations/test_checkout.py+++ b/saleor/graphql/meta/tests/mutations/test_checkout.py@@ -239,11 +239,13 @@ def test_add_public_metadata_for_checkout_by_token(api_client, checkout):@patch("saleor.plugins.manager.PluginsManager.checkout_updated")-def test_add_metadata_for_checkout_triggers_checkout_updated_hook(- mock_checkout_updated, api_client, checkout+def test_add_metadata_for_checkout_triggers_checkout_updated_hook_use_legacy_update_webhook_emission_on(+ mock_checkout_updated, api_client, checkout, site_settings):# givencheckout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])# whenresponse = execute_update_public_metadata_for_item(@@ -255,6 +257,25 @@ def test_add_metadata_for_checkout_triggers_checkout_updated_hook(mock_checkout_updated.assert_called_once_with(checkout, webhooks=set())+@patch("saleor.plugins.manager.PluginsManager.checkout_updated")+def test_add_metadata_for_checkout_triggers_checkout_updated_hook_use_legacy_update_webhook_emission_off(+ mock_checkout_updated, api_client, checkout, site_settings+):+ # given+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ # when+ response = execute_update_public_metadata_for_item(+ api_client, None, checkout_id, "Checkout"+ )++ # then+ assert response["data"]["updateMetadata"]["errors"] == []+ mock_checkout_updated.assert_not_called()++def test_add_private_metadata_for_checkout(staff_api_client, checkout, permission_manage_checkouts):@@ -406,11 +427,14 @@ def test_add_metadata_for_checkout_triggers_webhooks_with_checkout_updated(checkout_with_item,address,shipping_method,+ site_settings,):# given# Include item so shipping webhooks are emittedcheckout = checkout_with_item+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])mocked_send_webhook_request_sync.return_value = [](diff --git a/saleor/graphql/meta/tests/mutations/test_product.py b/saleor/graphql/meta/tests/mutations/test_product.pyindex 9dd15dabd2..d535480781 100644--- a/saleor/graphql/meta/tests/mutations/test_product.py+++ b/saleor/graphql/meta/tests/mutations/test_product.py@@ -131,7 +131,7 @@ def test_delete_public_metadata_for_product_media()-@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")def test_delete_private_metadata_for_product(updated_webhook_mock, staff_api_client, permission_manage_products, product):@@ -307,7 +307,7 @@ def test_delete_public_metadata_for_digital_content()-@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")def test_delete_public_metadata_for_product(updated_webhook_mock, staff_api_client, permission_manage_products, product):@@ -472,7 +472,7 @@ def test_add_public_metadata_for_digital_content()-@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")def test_add_public_metadata_for_product(updated_webhook_mock, staff_api_client, permission_manage_products, product):@@ -537,7 +537,7 @@ def test_add_public_metadata_for_product_variant(assert variant.updated_at > old_updated_at-@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")def test_add_private_metadata_for_product(updated_webhook_mock, staff_api_client, permission_manage_products, product):@@ -618,3 +618,407 @@ def test_add_private_metadata_for_product_media(assert item_contains_proper_private_metadata(response["data"]["updatePrivateMetadata"]["item"], media, media_id)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_update_metadata_for_product_with_use_legacy_update_webhook_emission_on(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ product_id,+ "Product",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ product,+ product_id,+ value="UpdatedValue",+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_update_metadata_for_product_with_use_legacy_update_webhook_emission_off(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ product_id,+ "Product",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ product,+ product_id,+ value="UpdatedValue",+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_update_private_metadata_for_product_use_legacy_update_webhook_emission_off(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ product_id,+ "Product",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ product,+ product_id,+ value="UpdatedPrivateValue",+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_update_private_metadata_for_product_use_legacy_update_webhook_emission_on(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ product_id,+ "Product",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ product,+ product_id,+ value="UpdatedPrivateValue",+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_delete_metadata_for_product_use_legacy_update_webhook_emission_on(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ product.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ product.save(update_fields=["metadata"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_products, product_id, "Product"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], product, product_id+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_called_once_with(product)+++@patch("saleor.plugins.manager.PluginsManager.product_updated")+@patch("saleor.plugins.manager.PluginsManager.product_metadata_updated")+def test_delete_metadata_for_product_use_legacy_update_webhook_emission_off(+ mocked_product_metadata_updated,+ mocked_product_updated,+ staff_api_client,+ permission_manage_products,+ product,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ product.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ product.save(update_fields=["metadata"])+ product_id = graphene.Node.to_global_id("Product", product.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_products, product_id, "Product"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], product, product_id+ )+ mocked_product_metadata_updated.assert_called_once_with(product)+ mocked_product_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_metadata_for_product_variant_with_use_legacy_update_webhook_emission_on(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ variant_id,+ "ProductVariant",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ variant,+ variant_id,+ value="UpdatedValue",+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_called_once_with(variant)+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_metadata_for_product_variant_with_use_legacy_update_webhook_emission_off(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_update_public_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ variant_id,+ "ProductVariant",+ value="UpdatedValue",+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ variant,+ variant_id,+ value="UpdatedValue",+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_private_metadata_for_product_variant_use_legacy_update_webhook_emission_off(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ variant_id,+ "ProductVariant",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ variant,+ variant_id,+ value="UpdatedPrivateValue",+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_private_metadata_for_product_variant_use_legacy_update_webhook_emission_on(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_products,+ variant_id,+ "ProductVariant",+ value="UpdatedPrivateValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ variant,+ variant_id,+ value="UpdatedPrivateValue",+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_called_once_with(variant)+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_delete_metadata_for_product_variant_use_legacy_update_webhook_emission_on(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ variant.save(update_fields=["metadata"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_products, variant_id, "ProductVariant"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], variant, variant_id+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_called_once_with(variant)+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_delete_metadata_for_product_variant_use_legacy_update_webhook_emission_off(+ mocked_variant_metadata_updated,+ mocked_variant_updated,+ staff_api_client,+ permission_manage_products,+ variant,+ site_settings,+):+ # given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ variant.save(update_fields=["metadata"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # when+ response = execute_clear_public_metadata_for_item(+ staff_api_client, permission_manage_products, variant_id, "ProductVariant"+ )++ # then+ assert item_without_public_metadata(+ response["data"]["deleteMetadata"]["item"], variant, variant_id+ )+ mocked_variant_metadata_updated.assert_called_once_with(variant)+ mocked_variant_updated.assert_not_called()diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.pyindex a7de339b0b..a23e53beed 100644--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py@@ -248,7 +248,7 @@ class TransactionEventReport(DeprecatedModelMutation):fields_to_update.append("app")fields_to_update.append("app_identifier")transaction.save(update_fields=fields_to_update)- if metadata:+ if metadata or private_metadata:call_event(manager.transaction_item_metadata_updated, transaction)@classmethoddiff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.pyindex 4bfdafbbef..2b72c82f02 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py@@ -2876,7 +2876,7 @@ def test_transaction_event_report_update_transaction_private_metadata(assert event.app_identifier == app_api_client.app.identifierassert event.app == app_api_client.appassert event.user is None- transaction_item_metadata_updated_mock.assert_not_called()+ transaction_item_metadata_updated_mock.assert_called_once()def test_transaction_event_report_message_limit_exceeded(diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_update.py b/saleor/graphql/product/mutations/product_variant/product_variant_update.pyindex 6d4e4d8d3e..a3991e1f93 100644--- a/saleor/graphql/product/mutations/product_variant/product_variant_update.py+++ b/saleor/graphql/product/mutations/product_variant/product_variant_update.py@@ -26,6 +26,7 @@ from ....core.utils import ext_ref_to_global_id_or_errorfrom ....core.validators import validate_one_of_args_is_in_mutationfrom ....meta.inputs import MetadataInputfrom ....plugins.dataloaders import get_plugin_manager_promise+from ....site.dataloaders import get_site_promisefrom ...types import ProductVariantfrom ...utils import clean_variant_skufrom ..utils import PRODUCT_VARIANT_UPDATE_FIELDS@@ -232,7 +233,11 @@ class ProductVariantUpdate(DeprecatedModelMutation):if product_update_fields:instance.product.save(update_fields=product_update_fields)- return bool(modified_instance_fields), metadata_modified, attribute_modified+ # variant modified if any field except metadata changed+ variant_modified = bool(+ set(modified_instance_fields) - {"metadata", "private_metadata"}+ )+ return variant_modified, metadata_modified, attribute_modified@classmethoddef _save_attributes(cls, instance, cleaned_input) -> bool:@@ -271,20 +276,27 @@ class ProductVariantUpdate(DeprecatedModelMutation):variant_modified: bool,attribute_modified: bool,metadata_modified: bool,+ use_legacy_webhooks_emission: bool,):- if variant_modified or attribute_modified or metadata_modified:- manager = get_plugin_manager_promise(info.context).get()+ manager = get_plugin_manager_promise(info.context).get()+ if (+ # if any variant related field has been changed+ variant_modified+ or attribute_modified+ # if any metadata has been changed and legacy emission is enabled+ or (metadata_modified and use_legacy_webhooks_emission)+ ):cls.call_event(manager.product_variant_updated, instance)- if metadata_modified:- cls.call_event(manager.product_variant_metadata_updated, instance)-channel_ids = models.ProductChannelListing.objects.filter(product_id=instance.product_id).values_list("channel_id", flat=True)# This will recalculate discounted prices for products.cls.call_event(mark_active_catalogue_promotion_rules_as_dirty, channel_ids)+ if metadata_modified:+ cls.call_event(manager.product_variant_metadata_updated, instance)+@classmethoddef handle_metadata(cls, instance, cleaned_input):metadata_list: list[MetadataInput] = cleaned_input.pop("metadata", None)@@ -339,6 +351,8 @@ class ProductVariantUpdate(DeprecatedModelMutation):cls.construct_instance(instance, cleaned_input)cls.clean_instance(info, instance)+ site = get_site_promise(info.context).get()+ use_legacy_webhooks_emission = site.settings.use_legacy_update_webhook_emissionvariant_modified, metadata_modified, attribute_modified = cls._save(instance_tracker, cleaned_input)@@ -349,6 +363,7 @@ class ProductVariantUpdate(DeprecatedModelMutation):variant_modified,attribute_modified,metadata_modified,+ use_legacy_webhooks_emission,)return cls.success_response(instance)diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.pyindex 7118ad3452..d2ccee8df4 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py@@ -3294,62 +3294,117 @@ UPDATE_METADATA_QUERY = """idname}+ errors {+ field+ code+ }}}"""+ ("model_field", "metadata_field"),+ [+ ("metadata", "metadata"),+ ("private_metadata", "privateMetadata"),+ ],+)@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")-def test_update_product_variant_with_metadata(- product_variant_metadata_updated_webhook_mock,- product_variant_updated_webhook_mock,+def test_update_product_variant_metadata_changed_legacy_webhook_on(+ product_variant_metadata_updated_mock,+ product_variant_updated_mock,staff_api_client,product,permission_manage_products,+ site_settings,+ model_field,+ metadata_field,):# Given- # - Variant metadata is empty+ site_settings.use_legacy_update_webhook_emission = True+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])variant = product.variants.first()+ variant.name = "Name"+ variant.save(update_fields=["name"])variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ metadata_key = "key"+ metadata_value = "value"- assert variant.metadata == {}- assert variant.private_metadata == {}+ variables = {+ "id": variant_id,+ "input": {+ metadata_field: [{"key": metadata_key, "value": metadata_value}],+ },+ }# When- # - Metadata is updated- # - No other attribute is updated- metadata_key = "mk"- metadata_value = "mv"+ response = staff_api_client.post_graphql(+ UPDATE_METADATA_QUERY, variables, permissions=[permission_manage_products]+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ data = content["data"]["productVariantUpdate"]++ # Then+ assert not data["errors"]+ assert getattr(variant, model_field)[metadata_key] == metadata_value+ product_variant_updated_mock.assert_called_once_with(variant)+ product_variant_metadata_updated_mock.assert_called_once_with(variant)+++ ("model_field", "metadata_field"),+ [+ ("metadata", "metadata"),+ ("private_metadata", "privateMetadata"),+ ],+)+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_product_variant_metadata_changed_legacy_webhook_off(+ product_variant_metadata_updated_mock,+ product_variant_updated_mock,+ staff_api_client,+ product,+ permission_manage_products,+ site_settings,+ model_field,+ metadata_field,+):+ # Given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+ variant = product.variants.first()variant.name = "Name"+ variant.save(update_fields=["name"])+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ metadata_key = "key"+ metadata_value = "value"variables = {"id": variant_id,"input": {- "metadata": [{"key": metadata_key, "value": metadata_value}],+ metadata_field: [{"key": metadata_key, "value": metadata_value}],},}+ # Whenresponse = staff_api_client.post_graphql(UPDATE_METADATA_QUERY, variables, permissions=[permission_manage_products])variant.refresh_from_db()content = get_graphql_content(response)- data = content["data"]["productVariantUpdate"]["productVariant"]-- assert data["id"] == variant_id+ data = content["data"]["productVariantUpdate"]# Then- # - Both variant_updated and variant_metadata_updated should run- # - Both should run only once- product_variant_updated_webhook_mock.assert_called_once_with(- product.variants.last()- )- product_variant_metadata_updated_webhook_mock.assert_called_once_with(- product.variants.last()- )+ assert not data["errors"]+ assert getattr(variant, model_field)[metadata_key] == metadata_value+ product_variant_updated_mock.assert_not_called()+ product_variant_metadata_updated_mock.assert_called_once_with(variant)@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")@@ -3412,16 +3467,13 @@ def test_update_product_variant_with_existing_metadata_and_no_event(variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)variant.name = "Name"-variant.metadata = {"Foo": "Bar",}-variant.private_metadata = {"Foo": "Bar",}-- variant.save()+ variant.save(update_fields=["name", "metadata", "private_metadata"])# When# - Variant attribute is being updated@@ -3469,12 +3521,9 @@ def test_update_product_variant_with_existing_metadata_and_no_event_when_write_tmetadata_value = "mv"variant.name = "Name"-variant.metadata = {metadata_key: metadata_value}-variant.private_metadata = {metadata_key: metadata_value}-- variant.save()+ variant.save(update_fields=["name", "metadata", "private_metadata"])assert variant.metadata == {metadata_key: metadata_value}@@ -3515,11 +3564,11 @@ def test_update_product_variant_with_existing_metadata_and_event_when_write_diffstaff_api_client,product,permission_manage_products,+ site_settings,):# Given# - Metadata in variant is already existing# - mutation writes the same metadata key but different value-variant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)@@ -3531,6 +3580,9 @@ def test_update_product_variant_with_existing_metadata_and_event_when_write_diffvariant.private_metadata = {metadata_key: metadata_value}variant.save()+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])+# When# - Metadata is updated with the same valuesvariables = {@@ -3551,10 +3603,10 @@ def test_update_product_variant_with_existing_metadata_and_event_when_write_diffassert data["id"] == variant_id# Then- # - product_variant_updated should run - metadata value changed+ # - product_variant_updated should not run - only metadata value changed# - product_variant_metadata_updated should run - metadata value changed# no empty event emitted- product_variant_updated_webhook_mock.assert_called_once()+ product_variant_updated_webhook_mock.assert_not_called()product_variant_metadata_updated_webhook_mock.assert_called_once()@@ -3739,3 +3791,86 @@ def test_update_product_variant_emit_event(if key not in non_variant_instance_fields:save_variant_mock.assert_called()save_variant_mock.reset_mock()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_product_variant_sku_and_name_changed(+ product_variant_metadata_updated_mock,+ product_variant_updated_mock,+ staff_api_client,+ product,+ permission_manage_products,+):+ # Given+ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ new_sku = "new-sku"+ new_name = "new-name"++ variables = {+ "id": variant_id,+ "input": {+ "sku": new_sku,+ "name": new_name,+ },+ }++ # When+ response = staff_api_client.post_graphql(+ UPDATE_METADATA_QUERY, variables, permissions=[permission_manage_products]+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ data = content["data"]["productVariantUpdate"]++ # Then+ assert not data["errors"]+ assert variant.sku == new_sku+ assert variant.name == new_name+ product_variant_updated_mock.assert_called_once_with(variant)+ product_variant_metadata_updated_mock.assert_not_called()+++@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_metadata_updated")+def test_update_product_variant_data_and_metadata_changed_legacy_webhook_off(+ product_variant_metadata_updated_mock,+ product_variant_updated_mock,+ staff_api_client,+ product,+ permission_manage_products,+ site_settings,+):+ # Given+ site_settings.use_legacy_update_webhook_emission = False+ site_settings.save(update_fields=["use_legacy_update_webhook_emission"])++ variant = product.variants.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ new_sku = "new-sku"+ metadata_key = "key"+ metadata_value = "value"++ variables = {+ "id": variant_id,+ "input": {+ "sku": new_sku,+ "metadata": [{"key": metadata_key, "value": metadata_value}],+ "privateMetadata": [{"key": metadata_key, "value": metadata_value}],+ },+ }++ # When+ response = staff_api_client.post_graphql(+ UPDATE_METADATA_QUERY, variables, permissions=[permission_manage_products]+ )+ variant.refresh_from_db()+ content = get_graphql_content(response)+ data = content["data"]["productVariantUpdate"]++ # Then+ assert not data["errors"]+ assert variant.sku == new_sku+ product_variant_updated_mock.assert_called_once_with(variant)+ product_variant_metadata_updated_mock.assert_called_once_with(variant)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1ebe131439..57b0fbc4ec 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -10060,6 +10060,13 @@ type Shop implements ObjectWithMetadata {"""Charge taxes on shipping."""chargeTaxesOnShipping: Boolean! @deprecated(reason: "Use `ShippingMethodType.taxClass` to determine whether taxes are calculated for shipping methods; if a tax class is set, the taxes will be calculated, otherwise no tax rate will be applied.")++ """+ Use legacy update webhook emission. When enabled, update webhooks (e.g. `customerUpdated`,`productVariantUpdated`) are sent even when only metadata changes. When disabled, update webhooks are not sent for metadata-only changes; only metadata-specific webhooks (e.g., `customerMetadataUpdated`, `productVariantMetadataUpdated`) are sent.++ Added in Saleor 3.22.+ """+ useLegacyUpdateWebhookEmission: Boolean @deprecated}"""@@ -20681,6 +20688,13 @@ input ShopSettingsInput {"""Charge taxes on shipping."""chargeTaxesOnShipping: Boolean @deprecated(reason: "To enable taxes for a shipping method, assign a tax class to the shipping method with `shippingPriceCreate` or `shippingPriceUpdate` mutations.")++ """+ Use legacy update webhook emission. When enabled, update webhooks (e.g. `customerUpdated`,`productVariantUpdated`) are sent even when only metadata changes. When disabled, update webhooks are not sent for metadata-only changes; only metadata-specific webhooks (e.g., `customerMetadataUpdated`, `productVariantMetadataUpdated`) are sent.++ Added in Saleor 3.22.+ """+ useLegacyUpdateWebhookEmission: Boolean @deprecated}"""diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.pyindex 95bc5b8339..d17dbe80b0 100644--- a/saleor/graphql/shop/mutations/shop_settings_update.py+++ b/saleor/graphql/shop/mutations/shop_settings_update.py@@ -7,7 +7,7 @@ from ....permission.enums import SitePermissionsfrom ....site.models import DEFAULT_LIMIT_QUANTITY_PER_CHECKOUTfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_SHOPfrom ...core.enums import WeightUnitsEnumfrom ...core.mutations import BaseMutation@@ -113,6 +113,19 @@ class ShopSettingsInput(graphene.InputObjectType):"`shippingPriceCreate` or `shippingPriceUpdate` mutations."),)+ # legacy settings+ use_legacy_update_webhook_emission = graphene.Boolean(+ description=(+ "Use legacy update webhook emission. "+ "When enabled, update webhooks (e.g. `customerUpdated`,"+ "`productVariantUpdated`) are sent even when only metadata changes. "+ "When disabled, update webhooks are not sent for metadata-only changes; "+ "only metadata-specific webhooks (e.g., `customerMetadataUpdated`, "+ "`productVariantMetadataUpdated`) are sent."+ + ADDED_IN_322+ + DEPRECATED_IN_3X_INPUT+ ),+ )class ShopSettingsUpdate(BaseMutation):diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.pyindex e3ed08e2ef..2de7005625 100644--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py@@ -23,6 +23,7 @@ SHOP_SETTINGS_UPDATE_MUTATION = """reserveStockDurationAuthenticatedUserlimitQuantityPerCheckoutallowLoginWithoutConfirmation+ useLegacyUpdateWebhookEmission}errors {field@@ -85,6 +86,7 @@ def test_shop_settings_mutation("fulfillmentAllowUnpaid": False,"enableAccountConfirmationByEmail": False,"allowLoginWithoutConfirmation": True,+ "useLegacyUpdateWebhookEmission": False,}}@@ -103,12 +105,14 @@ def test_shop_settings_mutation(assert data["fulfillmentAllowUnpaid"] is Falseassert data["enableAccountConfirmationByEmail"] is Falseassert data["allowLoginWithoutConfirmation"] is True+ assert data["useLegacyUpdateWebhookEmission"] is Falsesite_settings.refresh_from_db()assert not site_settings.include_taxes_in_pricesassert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shippingassert site_settings.enable_account_confirmation_by_email is Falseassert site_settings.allow_login_without_confirmation is True+ assert site_settings.use_legacy_update_webhook_emission is Falsedef test_shop_reservation_settings_mutation(diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 30ac4d49be..c17d3dc9be 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -389,6 +389,19 @@ class Shop(graphene.ObjectType):required=True,)+ # legacy settings+ use_legacy_update_webhook_emission = graphene.Boolean(+ description=(+ "Use legacy update webhook emission. "+ "When enabled, update webhooks (e.g. `customerUpdated`,"+ "`productVariantUpdated`) are sent even when only metadata changes. "+ "When disabled, update webhooks are not sent for metadata-only changes; "+ "only metadata-specific webhooks (e.g., `customerMetadataUpdated`, "+ "`productVariantMetadataUpdated`) are sent." + ADDED_IN_322+ ),+ deprecation_reason=DEFAULT_DEPRECATION_REASON,+ )+class Meta:description = ("Represents a shop resource containing general shop data and configuration."@@ -661,3 +674,8 @@ class Shop(graphene.ObjectType):return ObjectWithMetadata.resolve_private_metafields(site.settings, info, keys=keys)++ @staticmethod+ @load_site_callback+ def resolve_use_legacy_update_webhook_emission(_, _info, site):+ return site.settings.use_legacy_update_webhook_emissiondiff --git a/saleor/site/migrations/0043_sitesettings_use_legacy_update_webhook_emission.py b/saleor/site/migrations/0043_sitesettings_use_legacy_update_webhook_emission.pynew file mode 100644index 0000000000..62f0a2927f--- /dev/null+++ b/saleor/site/migrations/0043_sitesettings_use_legacy_update_webhook_emission.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.8 on 2025-11-25 12:29++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("site", "0042_sitesettings_refund_reason_reference_type"),+ ]++ operations = [+ migrations.AddField(+ model_name="sitesettings",+ name="use_legacy_update_webhook_emission",+ field=models.BooleanField(+ db_default=True,+ default=False,+ help_text="When enabled, update webhooks (e.g. `customerUpdated`,`productVariantUpdated`) are sent even when only metadata changes. When disabled, update webhooks are not sent for metadata-only changes; only metadata-specific webhooks (e.g., `customerMetadataUpdated`, `productVariantMetadataUpdated`) are sent.",+ ),+ ),+ ]diff --git a/saleor/site/models.py b/saleor/site/models.pyindex c0d59508e9..59dba28403 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -105,6 +105,19 @@ class SiteSettings(ModelWithMetadata):include_taxes_in_prices = models.BooleanField(default=True)display_gross_prices = models.BooleanField(default=True)+ # legacy settings+ use_legacy_update_webhook_emission = models.BooleanField(+ default=False,+ db_default=True,+ help_text=(+ "When enabled, update webhooks (e.g. `customerUpdated`,"+ "`productVariantUpdated`) are sent even when only metadata changes. "+ "When disabled, update webhooks are not sent for metadata-only changes; "+ "only metadata-specific webhooks (e.g., `customerMetadataUpdated`, "+ "`productVariantMetadataUpdated`) are sent."+ ),+ )+class Meta:permissions = ((SitePermissions.MANAGE_SETTINGS.codename, "Manage settings."),