Skip to content

Instantly share code, notes, and snippets.

@tedkulp
Created January 2, 2010 18:38
Show Gist options
  • Save tedkulp/267599 to your computer and use it in GitHub Desktop.
Save tedkulp/267599 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#Creates projects from approved estimates in Freshbooks
#(c)2010 Ted Kulp ted@tedkulp.com
#Requires the tedkulp-freshbooks.rb gem
#To install:
# sudo gem install tedkulp-freshbooks.rb
#
#Create a ~/.freshbooks file (yaml format) with 'url' and 'key' keys
#to set the URL and API keys for freshbooks
#require File.dirname(__FILE__) + '/freshbooks.rb/lib/freshbooks'
require 'rubygems'
gem 'tedkulp-freshbooks.rb'
require 'freshbooks'
require 'pp'
config = YAML::load(File.read(File.join(ENV['HOME'], '.freshbooks')))
#Connect to Freshbooks
#TODO: Do something nice if the url or key isn't correct or the server
#is down or any number of bad things
FreshBooks::Base.establish_connection(config['url'], config['key'])
#Grab a list of estimates -- wish they had an API call for estimates
#with search. C'est La Vie.
#TODO: Get multiple pages if they exist
estimates = FreshBooks::Estimate.list(:per_page => 100)
#puts estimates.size.to_s + "\n"
#Loop through all the found estimates and find the accepted ones
estimates.each do |estimate|
if estimate.status == 'accepted'
client_id = estimate.client_id
project_name = "Estimate #" + estimate.number.to_s
#Grab all projects with the given client id
#See if there is a project named after our found estimate
projects = FreshBooks::Project.list(:per_page => 100, :client_id => client_id)
found = false
projects.each do |project|
if project.name == project_name
found = true
end
end
#If none is found, create a new project with the given estimate number
if found == false
puts "Need to create a project for Estimate #" + estimate.number.to_s + "\n"
project = FreshBooks::Project.new
project.client_id = client_id
project.name = project_name
project.bill_method = 'staff-rate'
project.create
puts "Project ID: " + project.project_id.to_s + "\n"
#Hack to add all available tasks to the created project
#Their API kind of breaks here in that tasks aren't consistent
#between the list and update commands. Can't just use the Task
#class because it doesn't have the same syntax.
task_str = ''
tasks = FreshBooks::Task.list(:per_page => 100)
tasks.each do |task|
task_str = task_str + "<task_id>" + task.task_id.to_s + "</task_id>"
end
xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<request method=\"project.update\">
<project>
<project_id>" + project.project_id.to_s + "</project_id>
<tasks>" + task_str + "</tasks>
</project>
</request>"
FreshBooks::Base.connection.direct_post(xml)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment