Skip to content

Commit

Permalink
Add rake task to move all users from one organisation to another
Browse files Browse the repository at this point in the history
At the moment, we can only bulk move users from one organisation to
another by uploading a CSV file with their email addresses.

There may be circumstances in which we need to move all the users from
one department to another. For example the motivation to add this task
is that some users have been incorrectly assigned to an older, deleted
instance of an organisation.

Adding a rake task to enable us to do this without needing a CSV file.
  • Loading branch information
brucebolt committed Jan 21, 2025
1 parent 4da7470 commit adb0d13
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/tasks/data_hygiene.rake
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,15 @@ namespace :data_hygiene do
task :close_organisation, %i[content_id] => :environment do |_, args|
Organisation.find_by(content_id: args[:content_id]).update!(closed: true)
end

desc "Move all users from one organisation to another."
task :bulk_update_user_organisation, %i[old_content_id new_content_id] => :environment do |_, args|
old_organisation = Organisation.find_by(content_id: args[:old_content_id])
new_organisation = Organisation.find_by(content_id: args[:new_content_id])

users = User.where(organisation: old_organisation)
users.update_all(organisation_id: new_organisation.id)

puts "Moved #{users.count} users from #{old_organisation.name} to #{new_organisation.name}"
end
end
16 changes: 16 additions & 0 deletions test/lib/tasks/data_hygiene_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,20 @@ class DataHygieneTaskTest < ActiveSupport::TestCase
puts "Marked organisation #{organisation.name} as closed"
end
end

context "#bulk_update_user_organisation" do
should "update the organisation for matching users" do
old_organisation = create(:organisation, slug: "department-of-health-old")
new_organisation = create(:organisation, slug: "department-of-health-new")
another_organisation = create(:organisation, slug: "department-of-other-stuff")

user_1 = create(:user, organisation: old_organisation)
user_2 = create(:user, organisation: another_organisation)

Rake::Task["data_hygiene:bulk_update_user_organisation"].invoke(old_organisation.content_id, new_organisation.content_id)

assert_equal new_organisation, user_1.reload.organisation
assert_equal another_organisation, user_2.reload.organisation
end
end
end

0 comments on commit adb0d13

Please sign in to comment.