class Eco::API::UseCases::DefaultCases::ToCsvCase < Eco::API::Common::Loaders::UseCase name "to-csv" type :export attr_reader :session, :options, :people def main(people, session, options, usecase) @session = session; @options = options; @people = people unless people && !people.empty? session.logger.warn("No source people to create the file... aborting!") return false end unless file = options[:file] || options.dig(:export, :file, :name) session.logger.error("Destination file not specified") return false end session.logger.info("going to create file: #{file}") CSV.open(file, "w") do |csv| csv << spot_header people.each do |person| csv << target_entry_type(person).values end end exit(0) end private def target_entry_type(person) session.new_entry(person, dependencies: deps).yield_self do |person_entry| options.dig(:export, :options, :internal_names) ? person_entry.mapped_entry : person_entry.external_entry end end def deps @deps ||= {"supervisor_id" => {people: people}} end def spot_header entry = target_entry_type(people.first) header = entry.keys if options.dig(:nice_header) || options.dig(:export, :options, :nice_header) name_maps = session.schema.fields_by_alt_id.transform_values do |fld| fld.name end.merge({ "policy_group_ids" => "User Group(s)", "email" => "Email", "name" => "Name", "supervisor_id" => "Manager ID", "filter_tags" => "Locations", "default_tag" => "Default Location", "id" => "ecoPortal ID" }) header = header.map {|name| name_maps[name] ? name_maps[name] : name} end header end end