# frozen_string_literal: true require 'csv' module Redmine class CsvBaseService API_LOCATION = 'https://redmine.renuo.ch' def initialize(token) @token = token end def get http_response = http_request(generate_url) encoded_body = http_response.body.force_encoding('ISO-8859-1').encode('UTF-8') csv = parse_csv(encoded_body) parse_results(csv) end private def generate_url URI("#{API_LOCATION}/time_entries/report.csv?#{query}&key=#{@token}") end def http_request(url) req = Net::HTTP::Get.new(url) Net::HTTP.start(url.hostname, url.port, use_ssl: true) do |http| http.request(req) end end def query # to be implemented in concrete service end def parse_results(_csv) # to be implemented in concrete service end def parse_csv(body) separated_csv_entries = CSV.parse(body, col_sep: ',') keys = separated_csv_entries.shift[1..-2] entries = separated_csv_entries.shift[1..-2] keys.zip(entries).to_h rescue CSV::MalformedCSVError raise_bad_data_error end def raise_bad_data_error error = 'Malformed CSV, please use comma delimiters (Redmine language setting?)' Rails.logger.error error raise Redmine::BadData, error end end end