Skip to content

Instantly share code, notes, and snippets.

@fgasperij
Created April 19, 2016 14:50
Show Gist options
  • Save fgasperij/1e282b5e9099a0c908be62bdead8f655 to your computer and use it in GitHub Desktop.
Save fgasperij/1e282b5e9099a0c908be62bdead8f655 to your computer and use it in GitHub Desktop.
# Entries
# [
# {
# "id": 171009,
# "worker_id": 10,
# "record": "some work",
# "worked_at": "2013-09-02",
# "hours": 6,
# "client_id": 11,
# "project_id": 30,
# "billable_status": "billable"
# }
# ]
#
# Staff Hours
# {
# "total": 9999,
# "by_month": [
# ["2016-04-15", 99]
# ]
# }
require 'json'
require 'date'
require 'net/http'
module Config
API_TOKEN = 'SOME_TOKEN'
ENTRIES_URL = "http://brium.me/api/entries?access_token=#{API_TOKEN}"
BEFORE_BRIUM_FILENAME = 'staff_hours_before_brium.json'
STAFF_HOURS_FILENAME = 'staff_hours.json'
end
def update_staff_hours(entries_str)
hours_before_brium = parse_json_file(Config::BEFORE_BRIUM_FILENAME) # Staff format
hours_before_brium = keys_to_symbol(hours_before_brium)
entries = JSON.parse(entries_str)
hours_after_brium = process_entries(entries)
staff_hours = merge_periods(hours_before_brium, hours_after_brium)
staff_hours_json = staff_hours.to_json
update_staff_hours_file(staff_hours_json)
end
def keys_to_symbol(h)
h.inject({}) do |accum, (key, value)|
accum[key.to_sym] = value
accum
end
end
def update_staff_hours_file(staff_hours_json)
File.open(Config::STAFF_HOURS_FILENAME, 'w') do |f|
f.truncate(0)
f.write(staff_hours_json)
end
end
def merge_periods(left, right)
{
total: left[:total] + right[:total],
by_month: left[:by_month] + right[:by_month]
}
end
def process_entries(entries)
by_month = Hash.new 0
total_hours = 0
entries.each do |entry|
hours = entry["hours"]
total_hours += hours
date = Date.parse entry["worked_at"]
date_key = "#{date.year}-#{date.month}-01"
by_month[date_key.to_sym] += hours
end
by_month = by_month.to_a
by_month = by_month.map do |value|
date, hours = value
[date, hours.to_i]
end
{total: total_hours, by_month: by_month}
end
def parse_json_file(filename)
if !File.exist?(filename)
raise "#{filename} doesn't exist."
end
file = File.open(filename, 'r')
hash = JSON.parse file.read
file.close
hash
end
uri = URI.parse(Config::ENTRIES_URL)
response = Net::HTTP.get_response(uri)
if response.is_a? Net::HTTPSuccess
update_staff_hours(response.body)
else
puts "Request failed with a #{response.code}:\n #{response.body}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment