module Ecoportal module API class V1 # @attr_reader client [Common::Client] a `Common::Client` object that holds the configuration of the api connection. class People extend Common::BaseClass include Enumerable include Common::DocHelpers JOB_TIMEOUT = 240 DELAY_STATUS_CHECK = 5 class_resolver :person_class, "Ecoportal::API::V1::Person" attr_reader :client # @param client [Common::Client] a `Common::Client` object that holds the configuration of the api connection. # @return [People] an instance object ready to make people api requests. def initialize(client) @client = client end # Iterates all the people of the organization. # @note # - it ignores the key `cursor_id:` of `params:`. # - `each` is called by `to_a` # @param params [Hash] # @option params [String] :per_page the number of people you get per request. # @option params [String] :q some text to search. Omit this parameter to target all the people. # @param silent [Boolean] `false` to show percentage of progress. # @yield [person] does some stuff with the person. # @yieldparam person [Person] def each(params: {}, silent: false, &block) return to_enum(:each, params: params, silent: silent) unless block cursor_id = nil; results = 0 puts "\n" unless silent loop do params.update(cursor_id: cursor_id) if cursor_id response = client.get("/people", params: params) body = body_data(response.body) raise "Request failed - Status #{response.status}: #{body}" unless response.success? unless silent || (total = body["total_results"]) == 0 results += body["results"].length percent = results * 100 / total msg = "People GET" msg += " (search=#{params[:q]})" if params.key?(:q) print "#{msg}: #{percent.round}% (of #{total})\r" $stdout.flush end body["results"].each do |person| yield person_class.new(person) end break unless (cursor_id = body["cursor_id"]) end self end # Gets all the people via api requests. # @note it ignores the key `:cursor_id` in `params:`. # @param params [Hash] # @option params [Integer] :per_page the number of people you get per request. # @option params [String] :q some text to search. # @param silent [Boolean] `false` to show percentage of progress. # @return [Array] the array of people got via api. def get_all(params: {}, silent: false) each(params: params, silent: silent).to_a end # Gets a person via api. # @note if the request has `success?` the returned `object.result` gives an object with that `Person`. # @param doc [String, Hash, Person] data containing an `id` (internal or external) of the target person. # @return [Person] the person with `id` (internal or external) contained in `doc`. def get(doc) id = get_id(doc) response = client.get("/people/"+CGI.escape(id)) body = body_data(response.body) return person_class.new(body) if response.success? raise "Could not get person #{id} - Error #{reponse.status}: #{body}" end # Requests an update of a person via api. # @param doc [Person, Hash] data that at least contains an `id` (internal or external) of the target person. # @return [Response] an object with the api response. def update(doc) body = get_body(doc) id = get_id(doc) client.patch("/people/"+CGI.escape(id), data: body) end # Requests to create a person via api. # @param doc [Person, Hash] data that at least contains an `id` (internal or external) of the target person. # @return [Response] an object with the api response. def create(doc) body = get_body(doc) client.post("/people", data: body) end # Requests to update an existing person or if it does not exist, to create it, via api. # @param doc [Person, Hash] data that at least contains an `id` (internal or external) of the target person. # @return [Response] an object with the api response. def upsert(doc) body = get_body(doc) id = get_id(doc) client.post("/people/"+CGI.escape(id), data: body) end # Requests to completelly remove from an organization an existing person via api. # @param doc [Person, Hash] data that at least contains an `id` (internal or external) of the target person. # @return [Response] an object with the api response. def delete(doc) id = get_id(doc) client.delete("/people/"+CGI.escape(id)) end # Creates a `BatchOperation` and yields it to the given bock. # @yield [batch_op] adds multiple api requests for the current batch. # @yieldparam batch_op [BatchOperation] def batch(job_mode: true, &block) return job(&block) if job_mode operation = Common::BatchOperation.new("/people", person_class, logger: client.logger) yield operation # The batch operation is responsible for logging the output client.without_response_logging do client.post("/people/batch", data: operation.as_json).tap do |response| operation.process_response(response) end end end def job operation = Common::BatchOperation.new("/people", person_class, logger: client.logger) yield operation # The batch operation is responsible for logging the output job_id = create_job(operation) status = wait_for_job_completion(job_id) if status&.complete? operation.process_response job_result(job_id, operation) else raise "Job `#{job_id}` not complete. Probably timeout after #{JOB_TIMEOUT} seconds. Current status: #{status}" end end # Creates a new `Person` object. # @return [Person] new empty person object of the current version. def new person_class.new end private JobStatus = Struct.new(:id, :complete?, :errored?, :progress) def job_status(job_id) response = client.get("/people/job/#{CGI.escape(job_id)}/status") body = body_data(response.body) raise "Status error" unless response.success? JobStatus.new( body["id"], body["complete"], body["errored"], body["progress"] ) end def job_result(job_id, operation) # The batch operation is responsible for logging the output client.without_response_logging do client.get("/people/job/#{CGI.escape(job_id)}").tap do |response| operation.process_response(response) end end end def wait_for_job_completion(job_id) # timeout library is evil. So we make poor-man timeout. # https://jvns.ca/blog/2015/11/27/why-rubys-timeout-is-dangerous-and-thread-dot-raise-is-terrifying/ before = Time.now while true status = job_status(job_id) break status if status.complete? break status if Time.now >= before + JOB_TIMEOUT sleep(DELAY_STATUS_CHECK) status end end def create_job(operation) job_id = nil client.without_response_logging do client.post("/people/job", data: operation.as_json).tap do |response| job_id = body_data(response.body)["id"] end end job_id end # Hook for other api versions to obtain the raw data of a response # @note this was introduced to allow `v2` to reuse this class def body_data(body) body end end end end end require 'ecoportal/api/v1/schema_field_value' require 'ecoportal/api/v1/person_details' require 'ecoportal/api/v1/person'