Skip to content

Instantly share code, notes, and snippets.

@charlietfl
Created February 10, 2014 12:38
Show Gist options
  • Save charlietfl/8915132 to your computer and use it in GitHub Desktop.
Save charlietfl/8915132 to your computer and use it in GitHub Desktop.
my app test
if(checkLogin()){
var app = angular.module('harvest', ['ui.bootstrap']);
app.run(function($http,HARVEST_API){
if( harvest.newData){
harvest.newData.method='new_token';
$http.post('ajax.php',harvest.newData);
}
HARVEST_API.getAll('people',function(data){
angular.forEach(data,function(row){
var person=row.user;
var name=person.first_name +' '+person.last_name;
person.name=name;
HARVEST_API.people[person.id]=person;
})
});
})
}else{
window.location='auth.php';
}
app.factory('HARVEST_API',function($http){
var headers={headers:{'Content-Type':'application/json','Accept': 'application/json'}};
function HttpErr(err){
if(!api.err){
api.err=true;
alert('Error getting data from Harvest API\n\nStatus:'+err.status);
}
}
var api={
people:{},
projectNames:{},
projectCodes:{},
getAll:function(type,callback){
return $http.get(apiUrl(type),headers).then(function(res){
return res.data;
},HttpErr).then(callback);
},
getProjectTimeWithStartEnd:function(project_id,start,end,callback){
var path='projects/'+project_id+'/entries';
var urlParams='from='+start+'&to='+end;
var url=apiUrl(path,urlParams);
return $http.get(url,headers).then(function(res){
return res.data;
},HttpErr).then(callback);
},
storeProjectToSession:function(project,timesheets,callback){
var data={
method:'store_project',
project:project,
timesheets:timesheets
}
return $http.post('ajax.php', data).then(function(data){
return data.status;
}).then(callback);
}
}
return api;
})
app.controller('MainCtrl', function($scope, HARVEST_API, $q /*,PROJECTS*/ ) {
function convertDateForUrl(obj){
if(moment.isMoment(obj)){
return obj.format('YYYY-MM-DD').replace(/-/g,'');
}else{
return moment(obj).format('YYYY-MM-DD').replace(/-/g,'');
}
}
$scope.date=null/*new Date()*/;
function setInitialSTartDate(){
var mom=moment();
if(mom.day()===0){
mom.day(-7);
}
$scope.date=mom.toDate() ;
}
setInitialSTartDate();
$scope.harvestUrlDates={
from:null,
to:null
}
harvestUrlDates=$scope.harvestUrlDates;
$scope.showTimesheets=false;
$scope.pdfReady=false;
var maxDate=moment().add('days',8).toDate();
$scope.config={
timeframe :'week',
startDate : getMondayDate($scope.date),
maxStartDate:maxDate,
endDate : getSundayDate($scope.date),
minEndDate :$scope.date,
maxEndDate :maxDate
};/* alternative is "custom"*/
$scope.datePickerOptions = {
'year-format': "'yy'",
'starting-day': 1,
'show-weeks':false
};
$scope.$watch('config.timeframe',function(newVal,oldVal){
$scope.showTimesheets=false;
$scope.pdfReady=false;
if(oldVal=='custom'){
$scope.config.startDate=null;
//setInitialSTartDate();
}
})
function getMondayDate(date){
var mon=moment(+date);
var monday_moment=mon.weekday(1);
return monday_moment.toDate();
}
function getSundayDate(date){
var sun=moment(+date);
var sunday_moment=sun.weekday(7);
return sunday_moment.toDate();
}
function setHarvestUrlDates(){
$scope.harvestUrlDates.from=convertDateForUrl($scope.config.startDate);
$scope.harvestUrlDates.to=convertDateForUrl($scope.config.endDate);
}
setHarvestUrlDates();
//$scope.maxDate=moment().add('days',8).toDate();
$scope.startDateChange=function(){
var datePicked=$scope.config.startDate;
var config=$scope.config;
if(config.timeframe=='week'){
config.startDate=getMondayDate(datePicked);
config.endDate=getSundayDate(datePicked);
setHarvestUrlDates();
$scope.getProjectTimes();
}else{
// moment('2010-10-20').isAfter('2010-01-01', 'year');
config.endDate=null;
config.minEndDate=config.startDate;
setHarvestUrlDates();
$scope.showTimesheets=false;
/*if(moment($scope.config.startDate).isAfter( $scope.config.endDate) ){
}*/
}
}
$scope.endDateChange=function(){
var config=$scope.config;
if(moment(config.endDate).isBefore(config.startDate, 'day')){
alert('End date must be after start date');
return;
}else{
setHarvestUrlDates();
$scope.getProjectTimes();
}
}
/* $scope.dateChange=function(){
var mon=moment(+$scope.date);
var sun=moment(+$scope.date);
var monday_moment=mon.weekday(1);
*//* set date display to monday*//*
var mondayDate=monday_moment.toDate();
$scope.date=mondayDate;
var sunday_moment=sun.weekday(7);
var from=convertDateForUrl(monday_moment)
var to=convertDateForUrl(sunday_moment)
angular.extend($scope.harvestUrlDates,{from:from,to:to});
$scope.getProjectTimes();
}*/
$scope.startLoading=function(){
$scope.showTimesheets=false;
$scope.loading=true;
$scope.noResults=false;
$scope.firstLoad=true;
$scope.pdfReady=false;
}
$scope.calcOT = function() {
// $scope.resetTotals()
resetTotals($scope.project_totals);
/* process each persons weekly time*/
angular.forEach($scope.timesheets, function(weekly) {
resetTotals(weekly);
var days = {};
var CalcRule = $scope.OTRules;
var project_totals = $scope.project_totals;
var daily = {};
var days_worked_in_week = 0;
angular.forEach(weekly.rows, function(timesheet, index) {
if (!daily[timesheet.spent_at]) {
var newDay = daily[timesheet.spent_at] = {};
resetTotals(newDay);
newDay.rows = [];
days_worked_in_week++;
}
daily[timesheet.spent_at].rows.push(timesheet);
});
var dayOfWeek=0;
angular.forEach(daily, function(item, date) {
dayOfWeek++;
var day_accumulated = {
reg_time: 0,
time_half: 0,
time_double: 0,
hours: 0
}
angular.forEach(item.rows, function(timesheet, rowIndex) {
var reg_time, time_half, time_double;
var hours = timesheet.hours;
weekly.hours += hours;
project_totals.hours += hours;
day_accumulated.hours += hours;
/* reset OT fields*/
timesheet.time_half = 0;
timesheet.time_double = 0;
/* regular time */
var hoursLeftover;
var isSeventhDay = dayOfWeek ==7 && days_worked_in_week==7;
var allowed_reg_time = getAllowedRegTime(CalcRule, isSeventhDay);
if (day_accumulated.reg_time <= allowed_reg_time) {
var availableRegTime = allowed_reg_time - day_accumulated.reg_time;
reg_time = hours <= availableRegTime ? hours : availableRegTime;
day_accumulated.reg_time += reg_time;
hoursLeftover = hours > availableRegTime ? hours - availableRegTime : 0;
} else {
reg_time = 0;
hoursLeftover = hours;
}
timesheet.reg_time = reg_time;
weekly.reg_time += reg_time;
project_totals.reg_time += reg_time;
/* return if nothing left */
if (!hoursLeftover) {
return
}
/* CA OT Rules*/
if (CalcRule == 1) {
//var isSeventhDay = dayIndex == 6;
if (day_accumulated.time_half == 3.5 || isSeventhDay) {
time_half = 0;
} else {
var available_time_half = 3.5 - day_accumulated.time_half;
available_time_half = available_time_half < 0 ? 0 : available_time_half;
time_half = hoursLeftover <= available_time_half ? hoursLeftover : available_time_half;
hoursLeftover = hoursLeftover <= available_time_half ? 0 : hoursLeftover - available_time_half;
}
time_double = hoursLeftover;
}
/* no double time rule*/
if (CalcRule == 2) {
time_double = 0
time_half = hoursLeftover;
}
/* double time over 12 hours*/
if (CalcRule == 3) {
var available_time_half =2 - day_accumulated.time_half;
available_time_half = available_time_half < 0 ? 0 : available_time_half;
time_half = hoursLeftover <= available_time_half ? hoursLeftover : available_time_half;
hoursLeftover = hoursLeftover <= available_time_half ? 0 : hoursLeftover - available_time_half;
time_double = hoursLeftover;
}
timesheet.time_half = time_half;
weekly.time_half += time_half;
project_totals.time_half += time_half;
day_accumulated.time_half += time_half;
timesheet.time_double = time_double;
weekly.time_double += time_double;
project_totals.time_double += time_double;
day_accumulated.time_double += time_double;
});
})
});
/* calcs are done, send to server to store data for pdf*/
$scope.storeProject();
}
$scope.storeProject=function(){
console.log('Project for ajax',$scope.project)
var tmp=angular.copy($scope.project);
var project=angular.extend(tmp, $scope.project_totals);
HARVEST_API.storeProjectToSession(project,$scope.timesheets,function(status){
if(status){
$scope.pdfReady=true;
}
});
}
function getAllowedRegTime(CalcRule, isSeventhDay) {
if (CalcRule == 1) {
/*return isSeventhDay ? 8 : 8.5;*/
return 8 ;
}
return 10;
}
$scope.OTRules = 1;
$scope.$watch('OTRules', function(newVal, oldVal) {
if (!oldVal || newVal == oldVal) {
return
}
if (newVal) {
$scope.calcOT();
}
});
HARVEST_API.getAll('clients',function(data){
var clientIds=[]
var clients=[];
angular.forEach(data, function(client) {
var id=client.client.id;
clientIds.push(id);
clients.push( {id: id, name:client.client.name,projects:[] })
})
HARVEST_API.getAll('projects',function(projects){
angular.forEach(projects, function(row) {
/* used to refrence details for timesheeets*/
HARVEST_API.projectNames[row.project.id] = row.project.name;
HARVEST_API.projectCodes[row.project.id] = row.project.code;
var client_id=row.project.client_id;
var clientIndex=clientIds.indexOf(client_id);
clients[clientIndex].projects.push(row);
})
$scope.projects = projects;
$scope.clients=clients;
});
})
/*var start = '20140101',
end = '20140206';*/
$scope.project_totals = {};
$scope.project_id=null;
$scope.changeProject=function(project,client){
angular.forEach($scope.projects,function(item){
item.active=false;
})
project.active=true;
$scope.project_id=project.project.id;
$scope.project={
project_name: project.project.name,
project_code: project.project.code,
client:client.name/*,
start: $scope.harvestUrlDates.from,
end:$scope.harvestUrlDates.to*/
}
$scope.getProjectTimes();
}
$scope.getProjectTimes=function(/*project*/){
var start=$scope.harvestUrlDates.from;
var end=$scope.harvestUrlDates.to;
var project_id=$scope.project_id;
$scope.project_name=HARVEST_API.projectNames[project_id];
if(!(start && end && project_id)){
console.log('Project params failed[start,end,project_id]', start,end,project_id);
}else{
$scope.project.start=start;
$scope.project.end=end;
$scope.startLoading();
HARVEST_API.getProjectTimeWithStartEnd(project_id,start,end, function(data){
$scope.loading=false;
if(!data.length){
$scope.noResults=true;
$scope.showTimesheets=false;
return;
}else{
$scope.showTimesheets=true;
}
var project_name = HARVEST_API.projectNames[project_id];
var project_code = HARVEST_API.projectCodes[project_id];
var timesheets = {};
angular.forEach(data, function(item) {
var entry = item.day_entry;
var user_id = entry.user_id
var userName = HARVEST_API.people[user_id];
if (!timesheets[user_id]) {
timesheets[user_id] = {
user_id: user_id,
name: HARVEST_API.people[user_id].name,
project_name: project_name,
project_code: project_code,
total_hours: 0,
time_half: 0,
time_double: 0,
reg_time: 0,
hours: 0,
rows: []
}
}
timesheets[user_id].total_hours += entry.hours;
var row = {
id: entry.id,
user_id: user_id,
hours: entry.hours,
spent_at: entry.spent_at,
name: HARVEST_API.people[user_id].name,
"started-at": entry["started-at"] || '',
"ended-at": entry["ended-at"] || '',
notes: entry.notes
}
timesheets[user_id].rows.push(row)
});
//angular.forEach(timesheets)
$scope.timesheets = timesheets;
$scope.calcOT();
});
}
}
/*$scope.dateChange();*/
function resetTotals(obj) {
angular.extend(obj, {
reg_time: 0,
time_half: 0,
time_double: 0,
hours: 0
})
}
});
app.directive('timesheet',function(){
return{
templateUrl: 'timesheetTemplate'
}
});
/* harvest API allows getting daily using Day Of Year/Year in url*/
Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}
function checkLogin(){
var hasToken=!!window.harvest.access_token;
var hash=location.hash;
var hasHash=!!hash || hash.indexOf('access_token')>-1;
var loggedin= hasToken || hasHash;
if(!hasToken && hasHash){
harvest.newData=parseTokenFromUrl(hash);
location.hash='';
}
return loggedin;
}
function apiUrl(path, extra_params){
//var url=harvest.api_url+path+'?access_token='+/*encodeURIComponent(*/harvest.access_token/*)*/;
//var url=harvest.api_url+path+'?access_token='+encodeURI(harvest.access_token);
var url=harvest.api_url+path+'?access_token='+harvest.access_token;
if(extra_params){
url+='&'+extra_params;
}
return url;
}
function parseTokenFromUrl(hash){
var hashParts=hash.split('&');
var data={};
for(i=0;i<hashParts.length;i++){
var part=hashParts[i];
if(part.indexOf('access_token')!=-1){
var token=part.slice(part.indexOf('=')+1);
data['access_token']=token;
// console.log(token)
harvest.access_token=token;
}
if(part.indexOf('expires_in')!=-1){
data['expires_in']=part.split('=').pop();
}
}
return data;
}
/*$.ajaxSetup({headers:{'Content-Type':'application/json','Accept': 'application/json'}});
$( document ).ajaxSend(function( event, jqxhr, settings ) {
console.log(settings);
console.log(jqxhr)
})*/
function clear(){
$.get('ajax.php?method=delete_session',function(res){
console.log('Session delete',res);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment