Last active
March 16, 2016 11:17
-
-
Save magician11/878af6d705dfa9dce32c to your computer and use it in GitHub Desktop.
Get all billable hours for a project from Freshbooks
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
let getBillableHours = function(projectId) { | |
function sumTimes(times) { | |
let billableHours = 0; | |
for(let time of times) { | |
billableHours += parseFloat(time.hours); | |
} | |
return billableHours; | |
} | |
return new Promise((resolve, reject) => { | |
let timeEntries = new freshbooks.Time_Entry(); | |
let billableHours = 0; | |
timeEntries.list({project_id: projectId, per_page: 100}, function(err, times, options) { | |
if(err) { | |
reject(err); | |
} else { | |
// grab the first page of times | |
billableHours = sumTimes(times); | |
// if there are more pages to process, get those... | |
if(options.pages > 1) { | |
let pagesToProcess = []; | |
for(let i = 2; i <= options.pages; i++) { | |
pagesToProcess.push(new Promise((done, reject) => { | |
timeEntries.list({project_id: projectId, per_page: 100, page: i }, function(err, times, options) { | |
let extraHours = sumTimes(times); | |
done(extraHours); | |
}); | |
})); | |
} | |
Promise.all(pagesToProcess).then((extraTimes) => { | |
freshbooksData.billableHours = billableHours + extraTimes.reduce(function(a,b) { return a + b; }); | |
resolve(freshbooksData.billableHours); | |
}); | |
} else { | |
freshbooksData.billableHours = billableHours; | |
resolve(freshbooksData.billableHours); | |
} | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment