class Eco::API::UseCases::DefaultCases::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 |supers| inform(*supers, session.logger) end micro.with_each_subordinate(old_sup, people) do |subordinate| subordinate.supervisor_id = new_sup&.id supers.add(subordinate) end.tap do |subordinates| unless subordinates.length > 0 sup_str = "#{old_sup.external_id} (#{old_sup.name} - #{old_sup.email})" session.logger.error("There are no subordinates for supervisor #{sup_str}. Aborting...") exit(1) end end end private def get_supers(people) micro = session.micro old_id, new_id = get_super_ids(options) old_sup, new_sup = [nil, nil] micro.with_supervisor(old_id, people) do |supervisor| unless old_sup = supervisor session.logger.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| unless new_sup = supervisor session.logger.error("Couldn't find any user with that id (new-super): '#{new_id}'. Aborting...") exit(1) end end [old_sup, new_sup] end def get_super_ids(options) unless old_id = options.dig(:super, :old) session.logger.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) session.logger.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, logger) msg = "Switching supervisor '#{old_sup.name}' (#{old_sup.external_id}) " msg += "to '#{new_sup&.name}' (#{new_sup&.external_id})" logger.info(msg) end end