Created
July 8, 2015 21:07
-
-
Save nikz/451e6c739881a7b62923 to your computer and use it in GitHub Desktop.
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
require 'rubygems' | |
require 'httparty' | |
require 'active_support/all' | |
class TogglClient | |
USER_AGENT = "TogglToInvoicedGuide" | |
include HTTParty | |
base_uri "https://toggl.com/reports/api/v2/" | |
def initialize(api_token) | |
@basic_auth = { username: api_token, password: "api_token" } | |
end | |
def summary_report(workspace_id, since_date, until_date) | |
options = { | |
workspace_id: workspace_id, | |
since: since_date.strftime("%Y-%m-%d"), | |
until: until_date.strftime("%Y-%m-%d"), | |
user_agent: USER_AGENT, | |
grouping: "clients" | |
} | |
self.class.get("/summary", basic_auth: @basic_auth, query: options) | |
end | |
end | |
class InvoicedClient | |
include HTTParty | |
base_uri "https://api.invoiced.com" | |
def initialize(api_key) | |
@basic_auth = { username: api_key, password: "" } | |
end | |
def create_invoice(invoice_attributes) | |
self.class.post("/invoices", basic_auth: @basic_auth, body: invoice_attributes.to_json, headers: { "Content-Type" => "application/json" }) | |
end | |
def list_customers | |
self.class.get("/customers", basic_auth: @basic_auth) | |
end | |
end | |
toggl = TogglClient.new("YOUR_API_TOKEN") | |
invoiced = InvoicedClient.new("YOUR_API_KEY") | |
report = toggl.summary_report(YOUR_WORKSPACE_ID, 1.month.ago.beginning_of_month, 1.month.ago.end_of_month) | |
client_name = "Pied Piper" | |
client_group = report.parsed_response["data"].detect { |group| group["title"]["client"] == client_name } | |
invoice_items = client_group["items"].map do |item| | |
{ | |
description: item["title"]["time_entry"], | |
unit_cost: item["rate"] || 100, | |
quantity: item["time"] / 1000 | |
} | |
end | |
customer_response = invoiced.list_customers | |
invoiced_customer = customer_response.parsed_response["customers"].detect { |c| c["name"] == client_name } | |
invoice_details = { | |
name: "Invoice for #{1.month.ago.beginning_of_month.strftime("%B")}", | |
customer: invoiced_customer["id"], | |
items: invoice_items | |
} | |
result = invoiced.create_invoice(invoice_details) | |
puts result.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment