Last active
June 21, 2017 07:48
-
-
Save tokland/df8878d5f12c6372efc966eb73ad68e2 to your computer and use it in GitHub Desktop.
Get report hours from toggl.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source "https://ruby.taobao.org" | |
ruby "2.3.0" | |
gem "activesupport" | |
gem "togglv8" | |
gem "awesome_print" | |
gem "trollop" | |
group :development do | |
gem "byebug" | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# | |
# Get monthly reports from toggl.com: | |
# | |
# $ bundle && bundle exec ruby toggl_reports.rb [-d YYYY/MM] | |
# | |
require 'active_support/core_ext/enumerable' | |
require 'active_support/time' | |
require 'togglv8' | |
require 'trollop' | |
class TogglReports | |
def initialize(api_token:) | |
@api = TogglV8::API.new(api_token) | |
@reports = TogglV8::ReportsV2.new(api_token: api_token) | |
end | |
def by_projects(from:, to:) | |
@api.workspaces.flat_map do |workspace| | |
$stderr.puts("Workspace: %s" % workspace["name"]) | |
@reports.workspace_id = workspace["id"] | |
@reports.summary("", :since => from, :until => to).map do |entry| | |
{ | |
time: entry["time"].to_f / 3600 / 1000, | |
client: entry["title"]["client"] || "[NO CLIENT]", | |
project: entry["title"]["project"] || "[NO PROJECT]", | |
} | |
end | |
end | |
end | |
def self.by_project_for_month(api_token:, date: Date.current) | |
reports = TogglReports.new(api_token: api_token) | |
entries = reports.by_projects(from: date.beginning_of_month, to: date.end_of_month) | |
total_hours = entries.map { |entry| entry[:time] }.sum | |
entry_lines = entries.map { |entry| "%{client} - %{project}: %{time}h" % entry } | |
$stderr.puts("Month: %s" % date.strftime("%Y-%B")) | |
$stderr.puts("Total hours: %0.2f" % total_hours) | |
$stdout.puts(entry_lines.join("\n")) | |
end | |
end | |
if __FILE__ == $0 | |
token_dir = File.join(__dir__, "toggl-api-token.txt") | |
default_api_token = File.exists?(token_dir) ? File.read(token_dir).strip : "" | |
opts = Trollop::options do | |
opt(:api_token, "API token", :type => :string, :default => default_api_token) | |
opt(:date, "Date month (YYYY/MM)", :type => :string) | |
end | |
date = opts[:date] ? Time.parse(opts[:date]) : Date.current.prev_month | |
TogglReports.by_project_for_month(api_token: opts[:api_token], date: date) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment