diff --git a/lib/tasks/data_hygiene.rake b/lib/tasks/data_hygiene.rake index 4402dfb8d..0e4bd8a63 100644 --- a/lib/tasks/data_hygiene.rake +++ b/lib/tasks/data_hygiene.rake @@ -12,4 +12,15 @@ namespace :data_hygiene do organisation.update!(closed: true) puts "Marked organisation #{organisation.slug} as closed" 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.slug} to #{new_organisation.slug}" + end end diff --git a/test/lib/tasks/data_hygiene_test.rb b/test/lib/tasks/data_hygiene_test.rb index 9fb3dbc71..2ae674b46 100644 --- a/test/lib/tasks/data_hygiene_test.rb +++ b/test/lib/tasks/data_hygiene_test.rb @@ -16,4 +16,20 @@ class DataHygieneTaskTest < ActiveSupport::TestCase assert organisation.reload.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