diff --git a/lib/tasks/data_hygiene.rake b/lib/tasks/data_hygiene.rake index e037d1fa3..0e4bd8a63 100644 --- a/lib/tasks/data_hygiene.rake +++ b/lib/tasks/data_hygiene.rake @@ -5,4 +5,22 @@ namespace :data_hygiene do abort "bulk updating organisations encountered errors" end end + + desc "Mark an organisation as closed" + task :close_organisation, %i[content_id] => :environment do |_, args| + organisation = Organisation.find_by(content_id: args[:content_id]) + 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 new file mode 100644 index 000000000..2ae674b46 --- /dev/null +++ b/test/lib/tasks/data_hygiene_test.rb @@ -0,0 +1,35 @@ +require "test_helper" + +class DataHygieneTaskTest < ActiveSupport::TestCase + setup do + Signon::Application.load_tasks if Rake::Task.tasks.empty? + + $stdout.stubs(:write) + end + + context "#close_organisation" do + should "mark the organisation as closed" do + organisation = create(:organisation, slug: "department-of-health", closed: false) + + Rake::Task["data_hygiene:close_organisation"].invoke(organisation.content_id) + + 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