diff --git a/zerver/models.py b/zerver/models.py index 69ff825ecb..e51056f262 100644 --- a/zerver/models.py +++ b/zerver/models.py @@ -639,6 +639,17 @@ class Realm(models.Model): # TODO: Change return type to QuerySet[UserProfile] return UserProfile.objects.filter(realm=self, is_active=True).select_related() + def get_first_human_user(self) -> Optional["UserProfile"]: + """A useful value for communications with newly created realms. + Has a few fundamental limitations: + + * Its value will be effectively random for realms imported from Slack or + other third-party tools. + * The user may be deactivated, etc., so it's not something that's useful + for features, permissions, etc. + """ + return UserProfile.objects.filter(realm=self, is_bot=False).order_by("id").first() + def get_human_owner_users(self) -> QuerySet: return UserProfile.objects.filter( realm=self, is_bot=False, role=UserProfile.ROLE_REALM_OWNER, is_active=True diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 70b069f57f..a98b80f514 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -134,6 +134,24 @@ class PermissionTest(ZulipTestCase): admin_users = user_profile.realm.get_admin_users_and_bots(include_realm_owners=False) self.assertFalse(user_profile in admin_users) + def test_get_first_human_user(self) -> None: + realm = get_realm("zulip") + UserProfile.objects.filter(realm=realm).delete() + + UserProfile.objects.create( + realm=realm, email="bot1@zulip.com", delivery_email="bot1@zulip.com", is_bot=True + ) + first_human_user = UserProfile.objects.create( + realm=realm, email="user1@zulip.com", delivery_email="user1@zulip.com", is_bot=False + ) + UserProfile.objects.create( + realm=realm, email="user2@zulip.com", delivery_email="user2@zulip.com", is_bot=False + ) + UserProfile.objects.create( + realm=realm, email="bot2@zulip.com", delivery_email="bot2@zulip.com", is_bot=True + ) + self.assertEqual(first_human_user, realm.get_first_human_user()) + def test_updating_non_existent_user(self) -> None: self.login("hamlet") admin = self.example_user("hamlet")