Module: Reaper

Defined in:
lib/reaper.rb,
lib/reaper/version.rb

Defined Under Namespace

Classes: Config, Error, Main

Constant Summary collapse

HARVEST_CLIENT_ID =
'c4CbEqRlWx1ziSITWP03BwjN'
LOCAL_SERVER_PORT =
31390
LOGIN_FILE_PATH =
File.join(Dir.home, '.reaper')
CONFIG_FILE_PATH =
File.join(Dir.home, '.reaper_config')
VERSION =
"0.1.5"

Class Method Summary collapse

Class Method Details

.check_authObject



71
72
73
# File 'lib/reaper.rb', line 71

def check_auth
  abort('Cannot find cached login info. Please run `reaper login` first.') unless 
end

.list_projectsObject



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/reaper.rb', line 129

def list_projects
  check_auth

  puts "Fetching your project list..."
  response = request 'users/me/project_assignments'
  puts "Cannot fetch your project list, please try agian later." unless response

  puts ''

  projects = response['project_assignments']
  # puts JSON.pretty_generate projects
  
  projects = projects.map do |p|
    pcode = p['project']['code']
    pname = p['project']['name']
    desc = "[#{pcode}] #{pname}"
    tasks = p['task_assignments']

    {
      :project_id => p['project']['id'],
      :project_name => pname,
      :project_code => pcode,
      :desc => desc,
      :client => p['client']['name'],
      :tasks => tasks.map do |t|
        {
          'tid' => t['task']['id'],
          'name' => t['task']['name']
        }
      end
    }
  end

  max_chars = (projects.max_by { |p| p[:desc].length })[:desc].length

  clients = projects.group_by { |p| p[:client] }.to_h.sort.to_h
  
  clients.each do |k, v|
    puts k
    puts '-' * max_chars
    v.sort_by! { |p| p[:project_code] }
    v.each do |p|
      puts p[:desc]
    end
    puts ''
  end

  puts "Total: #{projects.size}"

  clients
end

.load_configObject



96
97
98
99
100
# File 'lib/reaper.rb', line 96

def load_config
  return false if !File.exist? CONFIG_FILE_PATH
  $config = YAML.load File.read(CONFIG_FILE_PATH)
  true
end

.openWebpage(link) ⇒ Object



27
28
29
# File 'lib/reaper.rb', line 27

def openWebpage(link)
  system("open", link)
end

.request(endpoint) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/reaper.rb', line 31

def request(endpoint)
  uri = URI("https://api.harvestapp.com/v2/#{endpoint}")
  req = Net::HTTP::Get.new(uri)
  req['Accept'] = "application/json"
  req['Authorization'] = "Bearer #{$token}"
  req['Harvest-Account-ID'] = $acc_id

  begin
    res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) { |http|
      http.request(req)
    }
  rescue
    abort 'Cannot send request. Please check your network connection and try again.'
  end

  if res.kind_of? Net::HTTPSuccess
    JSON.parse res.body
  else
    nil
  end
end

.request_delete(endpoint) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/reaper.rb', line 53

def request_delete(endpoint)
  uri = URI("https://api.harvestapp.com/v2/#{endpoint}")
  req = Net::HTTP::Delete.new(uri)
  req['Accept'] = "application/json"
  req['Content-Type'] = "application/json"
  req['Authorization'] = "Bearer #{$token}"
  req['Harvest-Account-ID'] = $acc_id
  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) { |http|
    http.request(req)
  }
  
  if res.kind_of? Net::HTTPSuccess
    JSON.parse res.body
  else
    nil
  end
end

.restore_login_infoObject



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/reaper.rb', line 75

def 
  return false if !File.exist? LOGIN_FILE_PATH
   = YAML.load File.read(LOGIN_FILE_PATH)
  if [:harvest_login]
     = [:harvest_login]
    token = [:token]
     = [:account_id]
    user_id = [:user_id]

    if token && !token.empty? && 
       && .is_a?(Integer) && 
      user_id && user_id.is_a?(Integer)
      $token = token
      $acc_id = 
      $user_id = user_id
      return true
    end
  end
  false
end

.rootObject



249
250
251
# File 'lib/reaper.rb', line 249

def root
  File.expand_path '../', File.dirname(__FILE__)
end

.show_config(config) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/reaper.rb', line 102

def show_config(config)
  puts "Reaper Configuration (version #{$config[:version]})"
  puts ''

  title = 'Global Settings'
  rows = []
  rows << ['Daily working hours negative offset', "#{$config[:daily_negative_offset]} hour(s)"]
  rows << ['Daily working hours positive offset', "#{$config[:daily_positive_offset]} hour(s)"]
  table = Terminal::Table.new :title => title, :rows => rows
  puts table

  puts ''

  title = 'Projects & Tasks Settings'
  headers = ['Project', 'Task', 'Percentage']

  rows = []
  $config[:tasks].each do |task|
    desc = "[#{task[:pcode]}] #{task[:pname]} (#{task[:client]})"
    rows << [desc.scan(/.{1,30}/).join("\n"), task[:tname], "#{(task[:percentage] * 100).round}%"]
  end

  table = Terminal::Table.new :title => title, :headings => headers, :rows => rows
  table.style = { :all_separators => true }
  puts table
end

.start_config_server(global_settings, projects, added_tasks) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/reaper.rb', line 181

def start_config_server(global_settings, projects, added_tasks)
  puts 'Launching the configuration page in your browser...'
  
  server = TCPServer.new LOCAL_SERVER_PORT
  
  while session = server.accept
    request = session.gets

    next unless request
    
    if match = request.match(/\/reaper-config\s+/i)
      template_path = File.join root, 'assets/reaper_config_template.html'

      template = File.read(template_path)
        .sub('"{{RPR_GLOBAL_SETTINGS}}"', "JSON.parse('#{global_settings.to_json}')")
        .sub('"{{RPR_PROJECTS}}"', "JSON.parse('#{projects.to_json}')")
        .sub('"{{RPR_ADDED_TASKS}}"', "JSON.parse('#{added_tasks.to_json}')")
        
      session.print "HTTP/1.1 200\r\n"
      session.print "Content-Type: text/html\r\n"
      session.print "\r\n"
      session.print template
    elsif match = request.match(/\/submitTimeEntries\?([\S]+)\s+HTTP/i)
      params = match.captures.first

      raw_config = params.split('&').map { |arg| arg.split '=' }.to_h

      max_index = raw_config.keys.select { |e| e =~ /p\d+/ }
        .map { |e| e[1..-1].to_i }
        .max

      tasks = []
      (max_index + 1).times do |n|
        tasks << {
          :pid => raw_config["p#{n}"].to_i,
          :tid => raw_config["t#{n}"].to_i,
          :percentage => raw_config["pct#{n}"].to_i / 100.0
        }
      end

      tasks.each do |t|
        proj = projects.select { |p| p['pid'] == t[:pid] }.first
        if proj
          task = proj['tasks'].select { |it| it['tid'] == t[:tid] }.first
          t[:pcode] = proj['code']
          t[:pname] = proj['name']
          t[:client] = proj['client']
          t[:tname] = task['name']
        end

        abort 'Something went wrong' unless proj && task
      end
      
      $config = {
        :version => '0.1.0',
        :daily_negative_offset => raw_config['no'].to_i,
        :daily_positive_offset => raw_config['po'].to_i,
        :tasks => tasks
      }
      
      session.close
      break
    end

    session.close
  end
end