class Eco::API::UseCases::Default::People::SwitchSupervisorCase < Eco::API::Common::Loaders::UseCase name "switch-supervisor" type :transform def main(people, session, _options, usecase) supers = session.new_job("main", "supers", :update, usecase, :core) old_sup, new_sup = get_supers(people).tap do |sups| inform(*sups) end micro.with_each_subordinate(old_sup, people) do |subordinate| subordinate.supervisor_id = new_sup&.id supers.add(subordinate) end.tap do |subordinates| next unless subordinates.empty? sup_str = "#{old_sup.external_id} (#{old_sup.name} - #{old_sup.email})" log(:error) { "There are no subordinates for supervisor #{sup_str}. Aborting..." } exit(1) end end private def get_supers(people) micro = session.micro old_id, new_id = get_super_ids(options) old_sup, new_sup = [nil, nil] # rubocop:disable Style/ParallelAssignment micro.with_supervisor(old_id, people) do |supervisor| unless (old_sup = supervisor) log(:error) { "Couldn't find any user with that id (old-super): '#{old_id}'. Aborting..." } exit(1) end end micro.with_supervisor(new_id, people) do |supervisor| next if (new_sup = supervisor) log(:error) { "Couldn't find any user with that id (new-super): '#{new_id}'. Aborting..." } exit(1) end [old_sup, new_sup] end def get_super_ids(options) unless (old_id = options.dig(:super, :old)) log(:error) { "You haven't specified the original supervisor. Aborting..." } exit(1) end # we could be setting the supervisor to nil unless options[:super].key?(:new) log(:error) { "You haven't specified the new supervisor. Aborting..." } exit(1) end [old_id, options.dig(:super, :new)] end def inform(old_sup, new_sup) msg = "Switching supervisor '#{old_sup.name}' (#{old_sup.external_id}) " msg += "to '#{new_sup&.name}' (#{new_sup&.external_id})" log(:info) { msg } end end