require 'json' require 'pp' require 'securerandom' # for uuid (perhaps metter to have structure i.e. Session:id-Batch:id) module Eco module API class Session class BatchStatus < Common::Session::BaseSession attr_reader :queue, :method attr_reader :root def initialize(e, queue:, method:) super(e) unless queue && queue.is_a?(Array) msg = "In batch operations you must batch an array. Received: #{queue}" logger.fatal(msg) raise msg end @method = method @queue = queue @hash = @queue.each_with_index.map do |entry, i| [entry, i] end.to_h @responses = Array(0..@queue.length-1) end def root=(object) @root = object end def [](key) @responses[to_index(key)] end def []=(key, response) @responses[to_index(key)] = response end def received?(key) !!self[key] end def success?(key) self[key]&.success? end def people raise "This batch wasn't a 'get'. Can't obtain people without 'get' method" unless method == "get" out = Array(0..queue.length-1) @responses.each_with_index do |respose, i| out[i] = response.result end out end def error_queries queue.each_with_index.map do |query,i| self[i].success? ? nil : query end.compact end def errors? queue.any? {|query| !self[query].success?} end def errors_count error_queries.length end def str_error(key) msg = "" unless success?(key) i = to_index(key) entry = queue[i] response = self[i] msg = "Error #{response.status}: #{response.body}\n" msg += "-- Failed to batch #{method} (entry #{i+1}). Person: #{person_ref(entry)}" end msg end def str_errors(sort: :by_status) queries = error_queries if sort == :by_status queries = error_queries.sort_by do |query| self[query].status end end strs = [] if queries.length > 0 strs = queries.map {|query| str_error(query)} end strs end def print_error(key) unless success?(key) logger.error(str_error(key)) end end def print_errors(sort: :by_status) strs = str_errors(sort: sort) if strs.length > 0 logger.error(strs.join("\n")) #strs.each {|str| logger.error(str)} else logger.info("There were no errors for the current batch '#{method}'!! ;)") end end private def person_ref(entry) is_person = entry.is_a?(Ecoportal::API::Internal::Person) || entry.is_a?(Ecoportal::API::V1::Person) ref = nil ref = "'#{entry.name}' ('#{entry.external_id}': '#{entry.email}')" if is_person ref end def to_index(key) key.is_a?(Integer) ? valid_index(index: key) : valid_index(entry: key) end def valid_index(index: nil, entry: nil) index ||= @hash[entry] unless index && index < @queue.length raise "You must provide either the index or the original entry object of the batch" end index end end end end end