Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
notifications: Send private messages for user profile modifications.
The Dance5e51b7d33cfd
diff --git a/starlight_help/src/content/docs/configure-automated-notices.mdx b/starlight_help/src/content/docs/configure-automated-notices.mdxindex 86043b87601..474284243c8 100644--- a/starlight_help/src/content/docs/configure-automated-notices.mdx+++ b/starlight_help/src/content/docs/configure-automated-notices.mdx@@ -95,6 +95,18 @@ entirely. The topic for these messages is “signups”.<SaveChanges /></FlattenedSteps>+### Notices about changes to user profile++When an administrator modifies your account settings, you will receive a private+message from Notification Bot listing the changes that were made. This includes+updates to your full name, [role](/help/roles-and-permissions), and [custom profiles+fields](/help/custom-profile-fields).++The notification will show both the old and new values for each field that was+changed, making it easy to see exactly what was modified. Only administrators+can change other users' profiles, and these notifications ensure that users are+always informed when such changes occur.+## Zulip update announcementsZulip announces new features and other important product changes via automateddiff --git a/zerver/actions/custom_profile_fields.py b/zerver/actions/custom_profile_fields.pyindex d26a5426d1e..45dfc8d27ef 100644--- a/zerver/actions/custom_profile_fields.py+++ b/zerver/actions/custom_profile_fields.py@@ -4,10 +4,12 @@ import orjsonfrom django.db import transactionfrom django.utils.translation import gettext as _+from zerver.actions.message_send import send_user_profile_update_notificationfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.external_accounts import DEFAULT_EXTERNAL_ACCOUNTS+from zerver.lib.mention import silent_mention_syntax_for_userfrom zerver.lib.streams import render_stream_description-from zerver.lib.types import ProfileDataElementUpdateDict, ProfileFieldData+from zerver.lib.types import ProfileDataElementUpdateDict, ProfileFieldData, UserProfileChangeDictfrom zerver.lib.users import get_user_ids_who_can_access_userfrom zerver.models import CustomProfileField, CustomProfileFieldValue, Realm, UserProfilefrom zerver.models.custom_profile_fields import custom_profile_fields_for_realm@@ -173,7 +175,11 @@ def notify_user_update_custom_profile_data(def do_update_user_custom_profile_data_if_changed(user_profile: UserProfile,data: list[ProfileDataElementUpdateDict],+ acting_user: UserProfile | None,+ notify: bool,) -> None:+ changes: list[UserProfileChangeDict] = []+for custom_profile_field in data:field_value, created = CustomProfileFieldValue.objects.get_or_create(user_profile=user_profile, field_id=custom_profile_field["id"]@@ -191,6 +197,8 @@ def do_update_user_custom_profile_data_if_changed(# we have nothing to do here for this field.continue+ old_value = get_custom_profile_field_display_value(field_value)+field_value.value = custom_profile_field_value_stringif field_value.field.is_renderable():field_value.rendered_value = render_stream_description(@@ -209,10 +217,45 @@ def do_update_user_custom_profile_data_if_changed(},)+ new_value = get_custom_profile_field_display_value(field_value)++ changes.append(+ UserProfileChangeDict(+ field_name=field_value.field.name,+ old_value=old_value,+ new_value=new_value,+ )+ )++ if changes and notify:+ send_user_profile_update_notification(+ user_profile=user_profile, acting_user=acting_user, changes=changes+ )+++def get_custom_profile_field_display_value(field_value: CustomProfileFieldValue) -> str:+ """Convert custom profile field value to human-readable string based on field type."""+ if not field_value.value:+ return ""+ type = field_value.field.field_type++ if type == CustomProfileField.SELECT:+ field_data_dict = orjson.loads(field_value.field.field_data)+ value_key = field_value.value+ return field_data_dict[value_key]["text"]++ if type == CustomProfileField.USER:+ user_ids = orjson.loads(field_value.value)+ users = UserProfile.objects.filter(id__in=user_ids).only("id", "full_name")+ users_mentions = [silent_mention_syntax_for_user(user) for user in users]+ return (", ").join(users_mentions)++ return field_value.value+@transaction.atomic(savepoint=False)def check_remove_custom_profile_field_value(- user_profile: UserProfile, field_id: int, acting_user: UserProfile+ user_profile: UserProfile, field_id: int, acting_user: UserProfile, notify: bool) -> None:try:custom_profile_field = CustomProfileField.objects.get(realm=user_profile.realm, id=field_id)@@ -226,6 +269,7 @@ def check_remove_custom_profile_field_value(field_value = CustomProfileFieldValue.objects.get(field=custom_profile_field, user_profile=user_profile)+ old_value = get_custom_profile_field_display_value(field_value)field_value.delete()notify_user_update_custom_profile_data(user_profile,@@ -236,6 +280,17 @@ def check_remove_custom_profile_field_value("type": custom_profile_field.field_type,},)+ if notify:+ changes: list[UserProfileChangeDict] = [+ UserProfileChangeDict(+ field_name=custom_profile_field.name,+ old_value=old_value,+ new_value="",+ )+ ]+ send_user_profile_update_notification(+ user_profile=user_profile, acting_user=acting_user, changes=changes+ )except CustomProfileField.DoesNotExist:raise JsonableError(_("Field id {id} not found.").format(id=field_id))except CustomProfileFieldValue.DoesNotExist:diff --git a/zerver/actions/data_import.py b/zerver/actions/data_import.pyindex 56d5e90942b..de5652575fd 100644--- a/zerver/actions/data_import.py+++ b/zerver/actions/data_import.py@@ -101,7 +101,10 @@ def import_slack_data(event: dict[str, Any]) -> None:)if importing_user.role != UserProfile.ROLE_REALM_OWNER:do_change_user_role(- importing_user, UserProfile.ROLE_REALM_OWNER, acting_user=importing_user+ importing_user,+ UserProfile.ROLE_REALM_OWNER,+ acting_user=importing_user,+ notify=False,)preregistration_realm.status = confirmation_settings.STATUS_USEDexcept UserProfile.DoesNotExist:diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.pyindex 9d9928ae7a3..4b0d1d27867 100644--- a/zerver/actions/message_send.py+++ b/zerver/actions/message_send.py@@ -41,7 +41,7 @@ from zerver.lib.exceptions import ()from zerver.lib.markdown import MessageRenderingResult, render_message_markdownfrom zerver.lib.markdown import version as markdown_version-from zerver.lib.mention import MentionBackend, MentionData+from zerver.lib.mention import MentionBackend, MentionData, silent_mention_syntax_for_userfrom zerver.lib.message import (SendMessageRequest,check_user_group_mention_allowed,@@ -81,6 +81,7 @@ from zerver.lib.thumbnail import manifest_and_get_user_upload_previews, rewrite_from zerver.lib.timestamp import timestamp_to_datetimefrom zerver.lib.topic import get_topic_display_name, participants_for_topicfrom zerver.lib.topic_link_util import get_stream_link_syntax+from zerver.lib.types import UserProfileChangeDictfrom zerver.lib.url_preview.types import UrlEmbedDatafrom zerver.lib.user_groups import (check_any_user_has_permission_by_role,@@ -2209,3 +2210,44 @@ def maybe_send_channel_events_notice(archived_channel_notice=archived_channel_notice,acting_user=acting_user,)+++def send_user_profile_update_notification(+ user_profile: UserProfile,+ acting_user: UserProfile | None,+ changes: list[UserProfileChangeDict],+) -> None:+ if (acting_user is not None and acting_user.id == user_profile.id) or user_profile.is_bot:+ return++ notification_bot = get_system_bot(settings.NOTIFICATION_BOT, user_profile.realm_id)++ def format_empty_value(value: str) -> str:+ """Return italicized 'None' for empty values, otherwise return the value."""+ if value == "":+ return "*None*"+ return value++ with override_language(user_profile.default_language):+ # We can't name which user made the change, since it was done either on the command line or via an automated job like LDAP synchronization.+ # It's still useful to tell the user about the update.+ if acting_user is None:+ message = _("The following changes have been made to your account.")+ else:+ user_mention = silent_mention_syntax_for_user(acting_user)+ message = _("{user} has made the following changes to your account.").format(+ user=user_mention+ )++ for i, change in enumerate(changes):+ message += _(+ "\n- **Old {field_name}:** {old_value}\n- **New {field_name}:** {new_value}\n"+ ).format(+ field_name=change["field_name"],+ old_value=format_empty_value(change["old_value"]),+ new_value=format_empty_value(change["new_value"]),+ )+ if i < len(changes) - 1:+ message += "____\n\n"++ internal_send_private_message(notification_bot, user_profile, message)diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.pyindex 4c5db724e06..f543c998bf5 100644--- a/zerver/actions/user_settings.py+++ b/zerver/actions/user_settings.py@@ -9,6 +9,7 @@ from django.utils.timezone import now as timezone_nowfrom confirmation.models import Confirmation, create_confirmation_linkfrom confirmation.settings import STATUS_REVOKED, STATUS_USED+from zerver.actions.message_send import send_user_profile_update_notificationfrom zerver.actions.presence import do_update_user_presencefrom zerver.lib.avatar import avatar_urlfrom zerver.lib.cache import (@@ -22,6 +23,7 @@ from zerver.lib.i18n import get_language_namefrom zerver.lib.queue import queue_event_on_commitfrom zerver.lib.send_email import FromAddress, clear_scheduled_emails, send_emailfrom zerver.lib.timezone import canonicalize_timezone+from zerver.lib.types import UserProfileChangeDictfrom zerver.lib.upload import delete_avatar_imagefrom zerver.lib.users import (can_access_delivery_email,@@ -223,7 +225,7 @@ def do_change_password(user_profile: UserProfile, password: str, commit: bool =@transaction.atomic(savepoint=False)def do_change_full_name(- user_profile: UserProfile, full_name: str, acting_user: UserProfile | None+ user_profile: UserProfile, full_name: str, acting_user: UserProfile | None, notify: bool) -> None:old_name = user_profile.full_nameif old_name == full_name:@@ -253,6 +255,17 @@ def do_change_full_name(bot_owner_user_ids(user_profile),)+ if notify:+ changes: list[UserProfileChangeDict] = [+ UserProfileChangeDict(+ field_name="full name",+ old_value=old_name,+ new_value=full_name,+ )+ ]++ send_user_profile_update_notification(user_profile, acting_user, changes)+def check_change_full_name(user_profile: UserProfile, full_name_raw: str, acting_user: UserProfile | None@@ -264,7 +277,7 @@ def check_change_full_name(new_full_name = check_full_name(full_name_raw=full_name_raw, user_profile=user_profile, realm=user_profile.realm)- do_change_full_name(user_profile, new_full_name, acting_user)+ do_change_full_name(user_profile, new_full_name, acting_user, notify=True)return new_full_name@@ -286,7 +299,7 @@ def check_change_bot_full_name(full_name=new_full_name,is_activation=False,)- do_change_full_name(user_profile, new_full_name, acting_user)+ do_change_full_name(user_profile, new_full_name, acting_user, notify=False)@transaction.atomic(durable=True)diff --git a/zerver/actions/users.py b/zerver/actions/users.pyindex fc6d6497fc4..a43566c7cfc 100644--- a/zerver/actions/users.py+++ b/zerver/actions/users.py@@ -14,6 +14,7 @@ from django.utils.timezone import now as timezone_nowfrom django.utils.translation import get_languagefrom zerver.actions.message_delete import do_delete_messages_by_sender+from zerver.actions.message_send import send_user_profile_update_notificationfrom zerver.actions.streams import bulk_remove_subscriptions, send_peer_remove_eventsfrom zerver.actions.user_groups import (do_send_user_group_members_update_event,@@ -46,7 +47,7 @@ from zerver.lib.streams import (stream_to_dict,)from zerver.lib.subscription_info import bulk_get_subscriber_peer_info-from zerver.lib.types import UserGroupMembersData+from zerver.lib.types import UserGroupMembersData, UserProfileChangeDictfrom zerver.lib.user_counts import realm_user_count_by_rolefrom zerver.lib.user_groups import (convert_to_user_group_members_dict,@@ -583,7 +584,7 @@ def send_stream_events_for_role_update(@transaction.atomic(savepoint=False)def do_change_user_role(- user_profile: UserProfile, value: int, *, acting_user: UserProfile | None+ user_profile: UserProfile, value: int, *, acting_user: UserProfile | None, notify: bool) -> None:# We want to both (a) take a lock on the UserProfile row, and (b)# modify the passed-in UserProfile object, so that callers see the@@ -599,6 +600,8 @@ def do_change_user_role(old_value = user_profile.roleif old_value == value:return++ old_role_name = user_profile.get_role_name()old_system_group = get_system_user_group_for_user(user_profile)previously_accessible_streams = get_streams_for_user(@@ -633,6 +636,18 @@ def do_change_user_role()send_event_on_commit(user_profile.realm, event, get_user_ids_who_can_access_user(user_profile))+ if notify:+ changes: list[UserProfileChangeDict] = [+ UserProfileChangeDict(+ field_name="role",+ old_value=old_role_name,+ new_value=user_profile.get_role_name(),+ )+ ]+ send_user_profile_update_notification(+ user_profile=user_profile, acting_user=acting_user, changes=changes+ )+UserGroupMembership.objects.filter(user_profile=user_profile, user_group=old_system_group).delete()diff --git a/zerver/lib/scim.py b/zerver/lib/scim.pyindex f3364b3d2fc..a15b21147ae 100644--- a/zerver/lib/scim.py+++ b/zerver/lib/scim.py@@ -340,7 +340,7 @@ class ZulipSCIMUser(SCIMUser):do_change_user_delivery_email(self.obj, email_new_value, acting_user=None)if role_new_value is not None:- do_change_user_role(self.obj, role_new_value, acting_user=None)+ do_change_user_role(self.obj, role_new_value, acting_user=None, notify=True)if is_active_new_value is not None and is_active_new_value:do_reactivate_user(self.obj, acting_user=None)diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.pyindex 94408026d55..5ae5080457c 100644--- a/zerver/lib/test_classes.py+++ b/zerver/lib/test_classes.py@@ -2382,7 +2382,7 @@ class ZulipTestCase(ZulipTestCaseMixin, TestCase):appropriate initial role; this is usually more readable anda bit faster."""- do_change_user_role(user, role, acting_user=None)+ do_change_user_role(user, role, acting_user=None, notify=False)def set_user_setting(self, user: UserProfile, setting_name: str, value: bool) -> None:with self.captureOnCommitCallbacks(execute=True):@@ -2391,10 +2391,12 @@ class ZulipTestCase(ZulipTestCaseMixin, TestCase):def set_user_custom_profile_data(self, user_profile: UserProfile, data: list[ProfileDataElementUpdateDict]) -> None:- do_update_user_custom_profile_data_if_changed(user_profile, data)+ do_update_user_custom_profile_data_if_changed(+ user_profile, data, acting_user=None, notify=False+ )def set_full_name(self, user_profile: UserProfile, full_name: str) -> None:- do_change_full_name(user_profile, full_name, acting_user=None)+ do_change_full_name(user_profile, full_name, acting_user=None, notify=False)def get_row_pks_in_all_tables() -> Iterator[tuple[str, set[int]]]:diff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex 8cb22b42bb4..d14056f178f 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -43,6 +43,12 @@ class ProfileDataElementUpdateDict(TypedDict):value: ProfileDataElementValue+class UserProfileChangeDict(TypedDict):+ field_name: str+ old_value: str+ new_value: str++ProfileData: TypeAlias = list[ProfileDataElement]FieldElement: TypeAlias = tuple[diff --git a/zerver/management/commands/bulk_change_user_name.py b/zerver/management/commands/bulk_change_user_name.pyindex b0113a84011..89912522f0c 100644--- a/zerver/management/commands/bulk_change_user_name.py+++ b/zerver/management/commands/bulk_change_user_name.py@@ -32,6 +32,6 @@ class Command(ZulipBaseCommand):user_profile = self.get_user(email, realm)old_name = user_profile.full_nameprint(f"{email}: {old_name} -> {new_name}")- do_change_full_name(user_profile, new_name, None)+ do_change_full_name(user_profile, new_name, None, notify=True)except CommandError:print(f"e-mail {email} doesn't exist in the realm {realm}, skipping")diff --git a/zerver/management/commands/change_user_role.py b/zerver/management/commands/change_user_role.pyindex 563716a97b7..b47eb04302c 100644--- a/zerver/management/commands/change_user_role.py+++ b/zerver/management/commands/change_user_role.py@@ -89,7 +89,7 @@ ONLY perform this on customer request from an authorized person."This realm does not have enough licenses to change a guest user's role.")old_role_name = UserProfile.ROLE_ID_TO_NAME_MAP[user.role]- do_change_user_role(user, new_role, acting_user=None)+ do_change_user_role(user, new_role, acting_user=None, notify=True)new_role_name = UserProfile.ROLE_ID_TO_NAME_MAP[user.role]print(f"Role for {user.delivery_email} changed from {old_role_name} to {new_role_name}."diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.pyindex e3ce60ca372..4869ae475e9 100644--- a/zerver/tests/test_audit_log.py+++ b/zerver/tests/test_audit_log.py@@ -191,15 +191,32 @@ class TestRealmAuditLog(ZulipTestCase):user_profile = self.example_user("hamlet")acting_user = self.example_user("iago")do_change_user_role(- user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=acting_user- )- do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_GUEST, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_REALM_OWNER, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_MODERATOR, acting_user=acting_user)- do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user)+ user_profile,+ UserProfile.ROLE_REALM_ADMINISTRATOR,+ acting_user=acting_user,+ notify=False,+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_GUEST, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_REALM_OWNER, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_MODERATOR, acting_user=acting_user, notify=False+ )+ do_change_user_role(+ user_profile, UserProfile.ROLE_MEMBER, acting_user=acting_user, notify=False+ )old_values_seen = set()new_values_seen = set()for event in RealmAuditLog.objects.filter(diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex acca7725c77..97b7687efc2 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -80,6 +80,7 @@ from zerver.lib.test_helpers import (HostRequestMock,create_s3_buckets,load_subdomain_token,+ most_recent_message,ratelimit_rule,read_test_image_file,use_s3_backend,@@ -7789,6 +7790,10 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):self.perform_ldap_sync(self.example_user("hamlet"))hamlet = self.example_user("hamlet")self.assertEqual(hamlet.full_name, "New Name")+ message = most_recent_message(hamlet)+ self.assertIn("The following changes have been made to your account", message.content)+ self.assertIn("**Old full name:** King Hamlet", message.content)+ self.assertIn("**New full name:** New Name", message.content)def test_update_with_hidden_emails(self) -> None:hamlet = self.example_user("hamlet")@@ -7967,7 +7972,7 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):mock.patch("zerver.actions.user_settings.do_change_full_name") as f,):self.perform_ldap_sync(hamlet2)- f.assert_called_once_with(*expected_call_args)+ f.assert_called_once_with(*expected_call_args, notify=True)# Get the updated model and make sure the full name is changed correctly:hamlet2 = get_user_by_delivery_email(email, test_realm)@@ -8098,6 +8103,15 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):user_profile=hamlet, field=field).valueself.assertEqual(field_value, test_case["expected_value"])+ # Verify that notification was sent for custom profile field updates+ message = most_recent_message(hamlet)+ self.assertIn("The following changes have been made to your account", message.content)+ # Check that both fields are mentioned in the notification+ for data in test_data:+ self.assertIn(f"**Old {data['field_name']}:**", message.content)+ self.assertIn(+ f"**New {data['field_name']}:** {data['expected_value']}", message.content+ )def test_update_non_existent_profile_field(self) -> None:with (diff --git a/zerver/tests/test_bots.py b/zerver/tests/test_bots.pyindex 66a94145fef..7420c68b6e8 100644--- a/zerver/tests/test_bots.py+++ b/zerver/tests/test_bots.py@@ -1622,7 +1622,9 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):email = "[email protected]"user_profile = self.get_bot_user(email)- do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile)+ do_change_user_role(+ user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile, notify=False+ )req = dict(role=UserProfile.ROLE_GUEST)diff --git a/zerver/tests/test_channel_access.py b/zerver/tests/test_channel_access.pyindex 784b430a4eb..d9d37c84a1d 100644--- a/zerver/tests/test_channel_access.py+++ b/zerver/tests/test_channel_access.py@@ -495,7 +495,9 @@ class AccessStreamTest(ZulipTestCase):)# Bot with admin privileges should also be part of the result.- do_change_user_role(test_bot, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=desdemona)+ do_change_user_role(+ test_bot, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=desdemona, notify=False+ )expected_private_user_ids.add(test_bot.id)self.assertCountEqual(can_access_stream_metadata_user_ids(private_stream), expected_private_user_idsdiff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 143f83fccae..40e7c91df68 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -1809,7 +1809,7 @@ class NormalActionsTest(BaseAction):# Test event for removing custom profile datawith self.verify_action() as events:check_remove_custom_profile_field_value(- self.user_profile, field_id, acting_user=self.user_profile+ self.user_profile, field_id, acting_user=self.user_profile, notify=False)check_realm_user_update("events[0]", events[0], "custom_profile_field")self.assertEqual(events[0]["person"]["custom_profile_field"].keys(), {"id", "value"})@@ -2604,7 +2604,7 @@ class NormalActionsTest(BaseAction):def test_change_full_name(self) -> None:now = timezone_now()with self.verify_action() as events:- do_change_full_name(self.user_profile, "Sir Hamlet", self.user_profile)+ do_change_full_name(self.user_profile, "Sir Hamlet", self.user_profile, notify=False)check_realm_user_update("events[0]", events[0], "full_name")self.assertEqual(RealmAuditLog.objects.filter(@@ -2618,7 +2618,7 @@ class NormalActionsTest(BaseAction):# Verify no operation if the value isn't changing.with self.verify_action(num_events=0, state_change_expected=False):- do_change_full_name(self.user_profile, "Sir Hamlet", self.user_profile)+ do_change_full_name(self.user_profile, "Sir Hamlet", self.user_profile, notify=False)self.assertEqual(RealmAuditLog.objects.filter(realm=self.user_profile.realm,@@ -2633,7 +2633,7 @@ class NormalActionsTest(BaseAction):cordelia = self.example_user("cordelia")self.user_profile = self.example_user("polonius")with self.verify_action(num_events=0, state_change_expected=False):- do_change_full_name(cordelia, "Cordelia", self.user_profile)+ do_change_full_name(cordelia, "Cordelia", self.user_profile, notify=False)def test_change_user_delivery_email_email_address_visibility_admins(self) -> None:do_change_user_setting(@@ -3455,7 +3455,7 @@ class NormalActionsTest(BaseAction):def test_change_bot_full_name(self) -> None:bot = self.create_bot("test")with self.verify_action(num_events=2) as events:- do_change_full_name(bot, "New Bot Name", self.user_profile)+ do_change_full_name(bot, "New Bot Name", self.user_profile, notify=False)check_realm_bot_update("events[1]", events[1], "full_name")def test_regenerate_bot_api_key(self) -> None:diff --git a/zerver/tests/test_example.py b/zerver/tests/test_example.pyindex f74b5d892f4..9b99b99e47e 100644--- a/zerver/tests/test_example.py+++ b/zerver/tests/test_example.py@@ -69,7 +69,7 @@ class TestBasicUserStuff(ZulipTestCase):# functions, like do_change_user_role. Modifying Django# objects and then using .save() can be buggy, as doing so can# fail to update caches, RealmAuditLog, or related tables properly.- do_change_user_role(hamlet, UserProfile.ROLE_REALM_OWNER, acting_user=iago)+ do_change_user_role(hamlet, UserProfile.ROLE_REALM_OWNER, acting_user=iago, notify=False)self.assertTrue(is_administrator_role(hamlet.role))# After we promote Hamlet, we also demote him. Testing state@@ -82,7 +82,7 @@ class TestBasicUserStuff(ZulipTestCase):# There are a few exceptions, where tests interact with the# filesystem (E.g. uploading files), which is generally# handled by the setUp/tearDown methods for the test class.- do_change_user_role(hamlet, UserProfile.ROLE_MODERATOR, acting_user=iago)+ do_change_user_role(hamlet, UserProfile.ROLE_MODERATOR, acting_user=iago, notify=False)self.assertFalse(is_administrator_role(hamlet.role))diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.pyindex 842c74ac0e6..14e61bb9677 100644--- a/zerver/tests/test_invite.py+++ b/zerver/tests/test_invite.py@@ -1501,7 +1501,7 @@ [email protected]""",hamlet = self.example_user("hamlet")self.login_user(hamlet)# Test we properly handle links in user full names- do_change_full_name(hamlet, "</a> https://www.google.com", hamlet)+ do_change_full_name(hamlet, "</a> https://www.google.com", hamlet, notify=False)result = self.invite("[email protected]", ["Denmark"])self.assert_json_success(result)diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.pyindex 9cae2ff983b..704cb11ce0a 100644--- a/zerver/tests/test_management_commands.py+++ b/zerver/tests/test_management_commands.py@@ -804,3 +804,102 @@ class TestSendZulipUpdateAnnouncements(ZulipTestCase):realm.refresh_from_db()self.assertEqual(realm.zulip_update_announcements_level, 5)+++class TestUserChangeNotifications(ZulipTestCase):+ def test_bulk_change_user_name_sends_notifications(self) -> None:+ hamlet = self.example_user("hamlet")+ bot = self.example_user("default_bot")+ realm = hamlet.realm++ # Count bot messages before changes+ from zerver.models import Message++ bot_messages_before = Message.objects.filter(+ realm_id=realm.id, recipient__type_id=bot.id+ ).count()++ import tempfile++ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".csv") as f:+ f.write(f"{hamlet.delivery_email},New Hamlet Name\n")+ f.write(f"{bot.delivery_email},New Bot Name\n")+ data_file = f.name++ try:+ # Run the bulk_change_user_name command+ with stdout_suppressed():+ call_command("bulk_change_user_name", data_file, f"--realm={realm.string_id}")++ # Verify the name was changed+ hamlet.refresh_from_db()+ self.assertEqual(hamlet.full_name, "New Hamlet Name")++ # Verify a notification was sent (acting_user=None means system change)+ message = most_recent_message(hamlet)+ self.assertIn(+ "The following changes have been made to your account.",+ message.content,+ )+ self.assertIn("**Old full name:** King Hamlet", message.content)+ self.assertIn("**New full name:** New Hamlet Name", message.content)++ # Verify bot's name was changed+ bot.refresh_from_db()+ self.assertEqual(bot.full_name, "New Bot Name")++ # Verify bot did NOT receive a notification+ bot_messages_after = Message.objects.filter(+ realm_id=realm.id, recipient__type_id=bot.id+ ).count()+ self.assertEqual(bot_messages_before, bot_messages_after)+ finally:+ os.unlink(data_file)++ def test_change_user_role_sends_notifications(self) -> None:+ hamlet = self.example_user("hamlet")+ realm = hamlet.realm++ # Hamlet starts as a member+ self.assertEqual(hamlet.role, UserProfile.ROLE_MEMBER)++ # Change hamlet's role to moderator via management command+ with stdout_suppressed():+ call_command(+ "change_user_role", hamlet.delivery_email, "moderator", f"--realm={realm.string_id}"+ )++ # Verify the role was changed+ hamlet.refresh_from_db()+ self.assertEqual(hamlet.role, UserProfile.ROLE_MODERATOR)++ # Verify a notification was sent (acting_user=None means system change)+ message = most_recent_message(hamlet)+ self.assertIn("The following changes have been made to your account", message.content)+ self.assertIn("**Old role:** Member", message.content)+ self.assertIn("**New role:** Moderator", message.content)++ # Change bot's role to moderator via management command+ bot = self.example_user("default_bot")++ # Count bot messages before changes+ from zerver.models import Message++ bot_messages_before = Message.objects.filter(+ realm_id=realm.id, recipient__type_id=bot.id+ ).count()++ with stdout_suppressed():+ call_command(+ "change_user_role", bot.delivery_email, "moderator", f"--realm={realm.string_id}"+ )++ # Verify bot's role was changed+ bot.refresh_from_db()+ self.assertEqual(bot.role, UserProfile.ROLE_MODERATOR)++ # Verify bot did NOT receive a notification+ bot_messages_after = Message.objects.filter(+ realm_id=realm.id, recipient__type_id=bot.id+ ).count()+ self.assertEqual(bot_messages_before, bot_messages_after)diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 4fbe8edf54c..cbaed835ecb 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -42,6 +42,7 @@ from zerver.lib.bulk_create import create_usersfrom zerver.lib.create_user import copy_default_settingsfrom zerver.lib.events import do_events_registerfrom zerver.lib.exceptions import JsonableError+from zerver.lib.mention import silent_mention_syntax_for_userfrom zerver.lib.send_email import clear_scheduled_emails, queue_scheduled_emails, send_future_emailfrom zerver.lib.stream_subscription import get_user_subscribed_streamsfrom zerver.lib.stream_topic import StreamTopicTarget@@ -49,6 +50,7 @@ from zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import (get_subscription,get_test_image_file,+ most_recent_message,reset_email_visibility_to_everyone_in_zulip_realm,simulated_empty_cache,)@@ -66,6 +68,7 @@ from zerver.lib.users import (from zerver.lib.utils import assert_is_not_nonefrom zerver.models import (CustomProfileField,+ CustomProfileFieldValue,Message,OnboardingStep,PreregistrationUser,@@ -264,7 +267,7 @@ class PermissionTest(ZulipTestCase):self.assertFalse(othello_dict["is_owner"])req = dict(role=UserProfile.ROLE_REALM_OWNER)- with self.capture_send_event_calls(expected_num_events=6) as events:+ with self.capture_send_event_calls(expected_num_events=7) as events:result = self.client_patch(f"/json/users/{othello.id}", req)self.assert_json_success(result)owner_users = realm.get_human_owner_users()@@ -274,7 +277,7 @@ class PermissionTest(ZulipTestCase):self.assertEqual(person["role"], UserProfile.ROLE_REALM_OWNER)req = dict(role=UserProfile.ROLE_MEMBER)- with self.capture_send_event_calls(expected_num_events=5) as events:+ with self.capture_send_event_calls(expected_num_events=6) as events:result = self.client_patch(f"/json/users/{othello.id}", req)self.assert_json_success(result)owner_users = realm.get_human_owner_users()@@ -286,7 +289,7 @@ class PermissionTest(ZulipTestCase):# Cannot take away from last ownerself.login("desdemona")req = dict(role=UserProfile.ROLE_MEMBER)- with self.capture_send_event_calls(expected_num_events=4) as events:+ with self.capture_send_event_calls(expected_num_events=5) as events:result = self.client_patch(f"/json/users/{iago.id}", req)self.assert_json_success(result)owner_users = realm.get_human_owner_users()@@ -325,7 +328,7 @@ class PermissionTest(ZulipTestCase):# Givethreq = dict(role=orjson.dumps(UserProfile.ROLE_REALM_ADMINISTRATOR).decode())- with self.capture_send_event_calls(expected_num_events=6) as events:+ with self.capture_send_event_calls(expected_num_events=7) as events:result = self.client_patch(f"/json/users/{othello.id}", req)self.assert_json_success(result)admin_users = realm.get_human_admin_users()@@ -336,7 +339,7 @@ class PermissionTest(ZulipTestCase):# Taketh awayreq = dict(role=orjson.dumps(UserProfile.ROLE_MEMBER).decode())- with self.capture_send_event_calls(expected_num_events=5) as events:+ with self.capture_send_event_calls(expected_num_events=6) as events:result = self.client_patch(f"/json/users/{othello.id}", req)self.assert_json_success(result)admin_users = realm.get_human_admin_users()@@ -418,12 +421,25 @@ class PermissionTest(ZulipTestCase):new_name = "new name"self.login("iago")hamlet = self.example_user("hamlet")+ iago = self.example_user("iago")+ old_name = hamlet.full_namereq = dict(full_name=new_name)result = self.client_patch(f"/json/users/{hamlet.id}", req)self.assert_json_success(result)hamlet = self.example_user("hamlet")self.assertEqual(hamlet.full_name, new_name)+ # Check that notification was sent+ message = most_recent_message(hamlet)+ self.assertEqual(message.recipient.type_id, hamlet.id)+ self.assertIn(+ f"{silent_mention_syntax_for_user(iago)} has made the following changes to your account.",+ message.content,+ )+ self.assertIn(+ f"**Old full name:** {old_name}\n- **New full name:** {new_name}", message.content+ )+def test_non_admin_cannot_change_full_name(self) -> None:self.login("hamlet")req = dict(full_name="new name")@@ -658,10 +674,12 @@ class PermissionTest(ZulipTestCase):user_email: str,new_role: int,) -> None:+ admin = self.example_user("desdemona")self.login("desdemona")user_profile = self.example_user(user_email)old_role = user_profile.role+ old_role_name = user_profile.get_role_name()old_system_group = get_system_user_group_for_user(user_profile)self.assertTrue(self.check_property_for_role(user_profile, old_role))@@ -674,9 +692,9 @@ class PermissionTest(ZulipTestCase):req = dict(role=orjson.dumps(new_role).decode())# The basic events sent in all cases on changing role are - one event- # for changing role and one event each for adding and removing user- # from system user group.- num_events = 3+ # for changing role, one event each for adding and removing user+ # from system user group and one event for sending a private notifications.+ num_events = 4if UserProfile.ROLE_MEMBER in [old_role, new_role]:# There is one additional event for adding/removing user from@@ -725,6 +743,18 @@ class PermissionTest(ZulipTestCase):self.assertEqual(person["user_id"], user_profile.id)self.assertTrue(person["role"], new_role)+ # Test notification is sent+ message = most_recent_message(user_profile)+ self.assertEqual(message.recipient.type_id, user_profile.id)+ self.assertIn(+ f"{silent_mention_syntax_for_user(admin)} has made the following changes to your account.",+ message.content,+ )+ self.assertIn(+ f"**Old role:** {old_role_name}\n- **New role:** {user_profile.get_role_name()}",+ message.content,+ )+def test_change_regular_member_to_guest(self) -> None:self.check_user_role_change("hamlet", UserProfile.ROLE_GUEST)@@ -777,6 +807,7 @@ class PermissionTest(ZulipTestCase):def test_admin_user_can_change_profile_data(self) -> None:realm = get_realm("zulip")+ iago = self.example_user("iago")self.login("iago")cordelia = self.example_user("cordelia")@@ -818,11 +849,64 @@ class PermissionTest(ZulipTestCase):)self.assert_json_success(result)- cordelia = self.example_user("cordelia")for field_dict in cordelia.profile_data():with self.subTest(field_name=field_dict["name"]):self.assertEqual(field_dict["value"], fields[field_dict["name"]])+ # Check notification+ message = most_recent_message(cordelia)+ self.assertIn(+ f"{silent_mention_syntax_for_user(iago)} has made the following changes to your account.",+ message.content,+ )++ # Map field names to their expected display values in the notification.+ # Some field types convert their stored values to human-readable display text.+ expected_display_values = {+ "Phone number": "short text data",+ "Biography": "long text data",+ "Favorite food": "short text data",+ "Favorite editor": "Vim", # SELECT field: "0" -> "Vim"+ "Birthday": "1909-03-05",+ "Favorite website": "https://zulip.com",+ "Mentor": silent_mention_syntax_for_user(cordelia),+ "GitHub username": "timabbott",+ "Pronouns": "she/her",+ }++ for field_name, display_value in expected_display_values.items():+ self.assertIn(+ f"**Old {field_name}:** *None*\n- **New {field_name}:** {display_value}",+ message.content,+ )++ # Test delete a custom profile field and notification+ phone_field_id = CustomProfileField.objects.get(name="Phone number", realm=realm).id+ deleted_field = [+ {+ "id": phone_field_id,+ "value": None,+ }+ ]+ result = self.client_patch(+ f"/json/users/{cordelia.id}", {"profile_data": orjson.dumps(deleted_field).decode()}+ )+ self.assert_json_success(result)++ self.assertFalse(+ CustomProfileFieldValue.objects.filter(+ user_profile=cordelia, field=phone_field_id+ ).exists()+ )++ message = most_recent_message(cordelia)+ expected_content = (+ f"{silent_mention_syntax_for_user(iago)} has made the following changes to your account.\n"+ f"- **Old Phone number:** {expected_display_values['Phone number']}\n"+ f"- **New Phone number:** *None*"+ )+ self.assertEqual(expected_content, message.content)+# Test admin user cannot set invalid profile datainvalid_fields = [(@@ -3366,7 +3450,7 @@ class DeleteUserTest(ZulipTestCase):)self.assertGreater(len(direct_message_group_with_hamlet_recipient_ids), 0)- do_change_full_name(hamlet, "some new name", acting_user=hamlet)+ do_change_full_name(hamlet, "some new name", acting_user=hamlet, notify=False)name_change_log = RealmAuditLog.objects.last()assert name_change_log is not Noneself.assertEqual(name_change_log.event_type, AuditLogEventType.USER_FULL_NAME_CHANGED)diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.pyindex 7f22b764afb..1d63ff72415 100644--- a/zerver/views/custom_profile_fields.py+++ b/zerver/views/custom_profile_fields.py@@ -310,7 +310,7 @@ def remove_user_custom_profile_data(with transaction.atomic(durable=True):for field_id in data:check_remove_custom_profile_field_value(- user_profile, field_id, acting_user=user_profile+ user_profile, field_id, acting_user=user_profile, notify=False)return json_success(request)@@ -325,6 +325,6 @@ def update_user_custom_profile_data() -> HttpResponse:validate_user_custom_profile_data(user_profile.realm.id, data, acting_user=user_profile)with transaction.atomic(durable=True):- do_update_user_custom_profile_data_if_changed(user_profile, data)+ do_update_user_custom_profile_data_if_changed(user_profile, data, user_profile, notify=True)# We need to call this explicitly otherwise constraints are not checkreturn json_success(request)diff --git a/zerver/views/registration.py b/zerver/views/registration.pyindex 611c889b437..79fb0b1d0eb 100644--- a/zerver/views/registration.py+++ b/zerver/views/registration.py@@ -795,9 +795,9 @@ def registration_helper(# transaction, to avoid security issues if the process is interrupted halfway,# e.g. leaving the user reactivated but with the wrong role.do_activate_mirror_dummy_user(user_profile, acting_user=user_profile)- do_change_user_role(user_profile, role, acting_user=user_profile)+ do_change_user_role(user_profile, role, acting_user=user_profile, notify=False)do_change_password(user_profile, password)- do_change_full_name(user_profile, full_name, user_profile)+ do_change_full_name(user_profile, full_name, user_profile, notify=False)do_change_user_setting(user_profile, "timezone", timezone, acting_user=user_profile)do_change_user_setting(user_profile,@@ -1261,10 +1261,15 @@ def realm_import_post_process(# to create this specific realm and cannot have been used# to finish creating an account yet.do_change_user_role(- importing_user, UserProfile.ROLE_REALM_OWNER, acting_user=importing_user+ importing_user,+ UserProfile.ROLE_REALM_OWNER,+ acting_user=importing_user,+ notify=False,)do_change_user_delivery_email(- importing_user, preregistration_realm.email, acting_user=importing_user+ importing_user,+ preregistration_realm.email,+ acting_user=importing_user,)preregistration_realm.status = confirmation_settings.STATUS_USEDdiff --git a/zerver/views/users.py b/zerver/views/users.pyindex e13226ce22b..d832d733cf8 100644--- a/zerver/views/users.py+++ b/zerver/views/users.py@@ -299,7 +299,7 @@ def update_user_backend(check_spare_license_available_for_changing_guest_user_role(user_profile.realm)- do_change_user_role(target, role, acting_user=user_profile)+ do_change_user_role(target, role, acting_user=user_profile, notify=True)if full_name is not None and target.full_name != full_name and full_name.strip() != "":# We don't respect `name_changes_disabled` here because the request@@ -313,7 +313,9 @@ def update_user_backend(assert not isinstance(entry.value, int)if entry.value is None or not entry.value:field_id = entry.id- check_remove_custom_profile_field_value(target, field_id, acting_user=user_profile)+ check_remove_custom_profile_field_value(+ target, field_id, acting_user=user_profile, notify=True+ )else:clean_profile_data.append({@@ -324,7 +326,9 @@ def update_user_backend(validate_user_custom_profile_data(target.realm.id, clean_profile_data, acting_user=user_profile)- do_update_user_custom_profile_data_if_changed(target, clean_profile_data)+ do_update_user_custom_profile_data_if_changed(+ target, clean_profile_data, user_profile, notify=True+ )if new_email is not None and target.delivery_email != new_email:assert user_profile.can_change_user_emails and user_profile.is_realm_admin@@ -499,7 +503,7 @@ def patch_bot_backend(elif not user_profile.is_realm_admin:raise OrganizationAdministratorRequiredError- do_change_user_role(bot, role, acting_user=user_profile)+ do_change_user_role(bot, role, acting_user=user_profile, notify=False)if bot_owner_id is not None and bot.bot_owner_id != bot_owner_id:try:diff --git a/zilencer/management/commands/populate_db.py b/zilencer/management/commands/populate_db.pyindex 5c1f3f7e5ec..56be3b2129d 100644--- a/zilencer/management/commands/populate_db.py+++ b/zilencer/management/commands/populate_db.py@@ -561,7 +561,9 @@ class Command(ZulipBaseCommand):assign_time_zone_by_delivery_email("[email protected]", "UTC")iago = get_user_by_delivery_email("[email protected]", zulip_realm)- do_change_user_role(iago, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None)+ do_change_user_role(+ iago, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None, notify=False+ )iago.is_staff = Trueiago.save(update_fields=["is_staff"])@@ -583,13 +585,15 @@ class Command(ZulipBaseCommand):)desdemona = get_user_by_delivery_email("[email protected]", zulip_realm)- do_change_user_role(desdemona, UserProfile.ROLE_REALM_OWNER, acting_user=None)+ do_change_user_role(+ desdemona, UserProfile.ROLE_REALM_OWNER, acting_user=None, notify=False+ )shiva = get_user_by_delivery_email("[email protected]", zulip_realm)- do_change_user_role(shiva, UserProfile.ROLE_MODERATOR, acting_user=None)+ do_change_user_role(shiva, UserProfile.ROLE_MODERATOR, acting_user=None, notify=False)polonius = get_user_by_delivery_email("[email protected]", zulip_realm)- do_change_user_role(polonius, UserProfile.ROLE_GUEST, acting_user=None)+ do_change_user_role(polonius, UserProfile.ROLE_GUEST, acting_user=None, notify=False)# These bots are directly referenced from code and thus# are needed for the test suite.@@ -832,6 +836,8 @@ class Command(ZulipBaseCommand):{"id": github_profile.id, "value": "zulip"},{"id": pronouns.id, "value": "he/him"},],+ None,+ notify=False,)do_update_user_custom_profile_data_if_changed(hamlet,@@ -849,6 +855,8 @@ class Command(ZulipBaseCommand):{"id": github_profile.id, "value": "zulipbot"},{"id": pronouns.id, "value": "he/him"},],+ None,+ notify=False,)# We need to create at least one scheduled message for Iago for the api-test# cURL example to delete an existing scheduled message.diff --git a/zproject/backends.py b/zproject/backends.pyindex d94b5c0963f..1309c2100c9 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -993,7 +993,7 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):)except JsonableError as e:raise ZulipLDAPError(e.msg)- do_change_full_name(user_profile, full_name, None)+ do_change_full_name(user_profile, full_name, None, notify=True)def sync_custom_profile_fields_from_ldap(self, user_profile: UserProfile, ldap_user: _LDAPUser@@ -1366,7 +1366,7 @@ class ZulipLDAPUser(_LDAPUser):# Change the role properly, updating system groups.updated_role = user_profile.roleuser_profile.role = original_role- do_change_user_role(user_profile, updated_role, acting_user=None)+ do_change_user_role(user_profile, updated_role, acting_user=None, notify=True)def _get_groups(self) -> _LDAPUserGroups:groups = super()._get_groups()@@ -1743,7 +1743,7 @@ def sync_user_profile_custom_fields("value": value,})- do_update_user_custom_profile_data_if_changed(user_profile, profile_data)+ do_update_user_custom_profile_data_if_changed(user_profile, profile_data, None, notify=True)@external_auth_method@@ -2164,7 +2164,7 @@ def social_auth_sync_user_attributes(# Based on the information collected above, sync what's needed for the user_profile.old_role = user_profile.roleif new_role is not None and old_role != new_role:- do_change_user_role(user_profile, new_role, acting_user=None)+ do_change_user_role(user_profile, new_role, acting_user=None, notify=True)backend.logger.info("Set role %s for user %s", UserProfile.ROLE_ID_TO_API_NAME[new_role], user_profile.id)