class Eco::API::UseCases::Default::People::Treat::SupersHierarchy < Eco::API::Common::Loaders::UseCase name "supers-hierarchy" type :export require_relative 'cli/supers_hierachy_cli' OUT_FOLDER = "sftp".freeze OUT_TIME_FORMAT = '%Y%m%dT%H%M%S'.freeze OUT_FILENAME = "supers_hierarchy".freeze attr_reader :people def main(people, _session, options, _usecase) options[:end_get] = false @people = people save!(hierarchy, file: output_filename) end private def hierarchy Eco::API::Common::People::SupervisorHelpers.supervisors_tree(people) end def save!(data, file:) ext = File.extname(file).downcase.delete(".") case ext when "txt" create_file(data, file: file, format: :txt) when "html" puts "html is still not supported" exit(1) # create_file(data, file: file, format: :html) when "json" puts "json is still not supported" exit(1) # create_file(data, file: file, format: :json) end end def create_file(tree, file:, format: :txt) File.open(file, "w") do |fd| fd << tree_to_str(tree, format: format) end log(:info) { "Generated file #{file}" } end def tree_to_str(tree, lev: 0, format: :txt) msg = "Required Hash tree structure. Given: #{tree.class}" raise msg unless tree.is_a?(Hash) "".tap do |str| tree.each do |entry, subtree| str << "#{" " * lev}#{lev.positive? ? "+-#{lev}- " : ""}" str << (entry.name || entry.email || entry.external_id || entry.id) str << " (#{entry.external_id}|#{entry.email}|#{entry.id})\n" str << tree_to_str(subtree, lev: lev + 1, format: format) unless !subtree || subtree.empty? end end end def output_filename(ext: 'txt') @output_filename ||= options.dig(:output, :file) || default_output_filename(ext: ext) end def default_output_filename(name = self.class::OUT_FILENAME, ext: nil) File.join(output_folder, "#{timestamp}_#{config.active_enviro}_#{name}.#{ext}") end def output_folder "#{config.active_enviro}/#{self.class::OUT_FOLDER}" end def timestamp(date = Time.now) date.strftime(self.class::OUT_TIME_FORMAT) end end