def do_delete_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None: if user_profile.realm.is_zephyr_mirror_realm: raise AssertionError("Deleting zephyr mirror users is not supported") do_deactivate_user(user_profile, acting_user=acting_user) subscribed_huddle_recipient_ids = set( Subscription.objects.filter( user_profile=user_profile, recipient__type=Recipient.HUDDLE ).values_list("recipient_id", flat=True) ) user_id = user_profile.id realm = user_profile.realm date_joined = user_profile.date_joined personal_recipient = user_profile.recipient with transaction.atomic(): user_profile.delete() # Recipient objects don't get deleted through CASCADE, so we need to handle # the user's personal recipient manually. This will also delete all Messages pointing # to this recipient (all private messages sent to the user). assert personal_recipient is not None personal_recipient.delete() replacement_user = create_user( force_id=user_id, email=f"deleteduser{user_id}@{get_fake_email_domain(realm)}", password=None, realm=realm, full_name=f"Deleted User {user_id}", active=False, is_mirror_dummy=True, force_date_joined=date_joined, ) subs_to_recreate = [ Subscription( user_profile=replacement_user, recipient=recipient, is_user_active=replacement_user.is_active, ) for recipient in Recipient.objects.filter(id__in=subscribed_huddle_recipient_ids) ] Subscription.objects.bulk_create(subs_to_recreate) RealmAuditLog.objects.create( realm=replacement_user.realm, modified_user=replacement_user, acting_user=acting_user, event_type=RealmAuditLog.USER_DELETED, event_time=timezone_now(), )