var timeApp = angular.module('timeApp', ['ngRoute', 'ui.grid', 'ui.grid.edit', 'ui.grid.cellNav', 'ui.grid.pinning']); /** * Map based storage service */ timeApp.factory('storeSvc', function () { var P_TIME = "time_"; var items = {}; var addKV = function (k, v) { items[k] = v; items[P_TIME + k] = new Date().getTime(); console.log("Added " + k + " :: " + v); }; var isExpiredK = function (k) { // expire these after 10 min... var time = items[P_TIME + k]; if (!time) return true; else return items[P_TIME + k] < ((new Date().getTime()) - (10 * 60 * 1000)); } var getK = function (k) { return items[k]; console.log("returned " + k + " :: " + items[k]); }; var removeK = function (k) { items[k] = null; }; var hasK = function (k) { return items[k] && (items[k] != null); }; return { add: addKV, get: getK, has: hasK, isExpired: isExpiredK, remove: removeK }; }); timeApp.config(function ($routeProvider) { $routeProvider .when("/", { templateUrl: "time/entryView.html", controller: "timeCtrl" }) .when("/project", { templateUrl: "project/projectView.html", controller: "projectCtrl" }).when("/project/:projectId/:taskId", { templateUrl: "project/projectView.html", controller: "projectCtrl" }) .when("/entry", { templateUrl: "time/entryView.html", controller: "timeCtrl" }) .when("/entry/:id", { templateUrl: "time/entryView.html", controller: "timeCtrl" }) .when("/report", { templateUrl: "report/reportView.html", controller: "reportCtrl" }) .when("/reportUsers", { templateUrl: "report/reportUsersView.html", controller: "reportUsersCtrl" }) .when("/calendar", { templateUrl: "calendar/calendarView.html", controller: "calendarCtrl" }) .when("/invoice", { templateUrl: "invoice/invoiceView.html", controller: "invoiceCtrl" }) .when("/rate", { templateUrl: "invoice/rateView.html", controller: "rateCtrl" }) .when("/jira", { templateUrl: "jira/jiraView.html", controller: "jiraCtrl" }) .when("/tools", { templateUrl: "jira/toolsView.html", controller: "toolsCtrl" }) .when("/rss", { templateUrl: "jira/rssView.html", controller: "rssCtrl" }) .when("/sow", { templateUrl: "project/sowView.html", controller: "sowCtrl" }) .when("/user", { templateUrl: "user/userView.html", controller: "userCtrl" }) .when("/profile", { templateUrl: "user/profileView.html", controller: "profileCtrl" }); }); /** * Main Ctrl that wraps the body, used to manage global elements */ timeApp.controller('mainCtrl', function ($scope, $http, $window, storeSvc) { // generic progress bar for long operations $scope.showProgress = false; //show only the active users? $scope.activeOnly = true; /** * The last time (in ms) when the calendar events were reloaded from Google * @type {number} */ $scope.lastCalReload = 0; $scope.getLastCalReload = function () { return $scope.lastCalReload; } $scope.setLastCalReload = function () { $scope.lastCalReload = new Date().getTime(); } $scope.shouldLastCalReload = function () { //five mins ago var ago = (new Date().getTime()) - (5 * 60 * 1000) if (!$scope.lastCalReload || $scope.lastCalReload === 0) { return true; } else { if ($scope.lastCalReload > 0 && $scope.lastCalReload < ago) { return true } } return false; } /** * Iterate and call itemFunction on each element * @param array * @param itemFunction */ $scope.loop = function (array, itemFunction) { if (array && array.length > 0) { for (var r = 0; r < array.length; r++) itemFunction(array[r], r); } return array; }; $scope.profile = null; $scope.logError = function (errorResponse) { alert("Received an error " + errorResponse.status + ", are you logged in and have the right permissions set?" + "\n\n" + errorResponse.data); }; // $scope.setProfile = function (profile) { // $scope.profile = profile; // $scope.$broadcast('profile-loaded'); // $scope.$apply(); // }; $scope.projects = null; // global list of all projects $scope.users = null; // global list of all users $scope.managers = []; //a list of all managers, set selected to true $scope.manager = {id: 0, name: "Show All"}; /** * Load the users * @param callback */ $scope.loadUsers = function (activeOnly, callback) { $scope.activeOnly = activeOnly; //check the cach var reload = true; //Disabling DB, so you can pull only the active users (or not) // var users = storeSvc.get('users'); // if(users){ // check expired // reload = storeSvc.isExpired('users'); // } // if(!reload) return; if (!$scope.managers || $scope.managers.length === 0) { $http.get("/api/time/?a=manager").then(function (response) { $scope.managers = response.data; if($scope.managers) { $scope.managers.unshift({id: -1, name: "Hide All"}); $scope.managers.unshift({id: 0, name: "Show All"}); } } ); } $http.get("/api/time/?a=user¤t=" + ($scope.profile ? $scope.profile.email : 'NONE') + "&activeOnly=" + $scope.activeOnly).then(function (response) { $scope.users = response.data; // by default select all users.. if ($scope.users && $scope.users.length > 0) { console.log("got back " + $scope.users.length + " users") for (var g = 0; g < $scope.users.length; g++) { //only select the current user $scope.users[g].selected = false; $scope.users[g].managerShow = true; if (("" + $scope.users[g].email).toLowerCase() === ("" + $scope.profile.email).toLowerCase()) { console.log("Setting userId to " + $scope.users[g].id); $scope.profile.userId = $scope.users[g].id; // select the current user $scope.users[g].selected = true; //add fields to profile: $scope.profile.admin = $scope.users[g].admin; } } } //store: // storeSvc.add('users', $scope.users); if (callback) callback(); else $scope.$broadcast('users-loaded'); }, $scope.logError); } ; $scope.forceLoadProjects = function () { console.log("reloading projects start") $http.get("/api/time/?a=project").then(function (response) { $scope.projects = response.data; storeSvc.add('projects', $scope.projects); console.log("reloading projects end") $scope.$broadcast('projects-loaded'); }, $scope.logError); }; $scope.loadProjects = function (callback) { var reload = true; if (storeSvc.get('projects') && !storeSvc.isExpired('projects')) { reload = false; } if (!reload) return; $http.get("/api/time/?a=project").then(function (response) { $scope.projects = response.data; storeSvc.add('projects', $scope.projects); if (callback) callback(); else $scope.$broadcast('projects-loaded'); }, $scope.logError); }; $scope.initPage = function (callback) { $scope.profile = $window.profile; $scope.$broadcast('profile-loaded'); $scope.loadUsers($scope.activeOnly, callback); $scope.loadProjects(callback); }; $scope.tab = 'entry'; // entry, project, user /** * Sets the name of the active tab * @param tabName */ $scope.setTab = function (tab) { $scope.tab = tab; }; /** * turn a date number to mm/dd/yyyy * @param dateStr * @returns {string} */ $scope.formatDateStr = function (dateStr) { return $scope.formatDate(new Date(dateStr).getTime()); }; $scope.formatDate = function (timestamp) { var d = new Date(timestamp); return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear(); }; $scope.getMinutes = function (from, to) { var fromDate = new Date(from); var toDate = new Date(to); return (toDate - fromDate) / (60 * 1000); }; /** * Scan $scope.users, get the user by id * @param userId * @returns {*} */ $scope.getUser = function (userId) { if (typeof userId === 'string' || userId instanceof String) { userId = parseInt(userId, 10); } var res = false; if ($scope.users && $scope.users.length) { //$scope.users.find(ur => ur.id === userId); for (var t = 0; !res && t < $scope.users.length; t++) { if ($scope.users[t].id === userId) { res = $scope.users[t]; } } } return !res ? {name: ''} : res; }; /** * Abbreaviate a string, add ... after the len * @param value * @param len * @returns {string|*} */ $scope.abbreviate = function (value, len) { if (!value) return; if (!len) len = 25; if (value.length > len) return value.substr(0, len) + "..."; else return value; }; /** * Abbreaviate a string, add ... after the len * @param value * @param len * @returns {string|*} */ $scope.toFixedNumber = function (val) { if(!val) return; if(val === "") return 0.00; try { if(typeof val === 'number'){ return val.toFixed(2); } else { return Number(val).toFixed(2); } } catch (err){ return val; } }; $scope.tableToExcel2 = (function () { var table = document.getElementById('billedLinesEntries'); var tableExport = ''+ table.innerHTML + '
'; var myBlob = new Blob( [tableExport] , {type:'application/vnd.ms-excel'}); var url = window.URL.createObjectURL(myBlob); var a = document.createElement("a"); document.body.appendChild(a); a.href = url; a.download = "export.xls"; a.click(); //adding some delay in removing the dynamically created link solved the problem in FireFox setTimeout(function() {window.URL.revokeObjectURL(url);},0); }); /** * Export a table to excel, call using tableToExcel('someDivId', 'fileName'); * @type {function(...[*]=)} */ $scope.tableToExcel = (function () { var uri = 'data:application/vnd.ms-excel;base64,', template = '{table}
' , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) } return function (table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) } })(); var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; /** * get Sun from 0 or Sat from 6 */ $scope.getDay = function (dateStr) { return weekdays[(new Date(dateStr)).getDay()]; }; $scope.getFirst = function () { for (var i = 0, j = arguments.length; i < j; i++) { if (arguments[i]) return arguments[i]; } }; /** * used yo sign in, send a link to the user with the email */ $scope.sendLink = function (){ $http.get("/api/signin/?a=sendLink&emailLink="+$scope.emailLink).then(function (response) { alert("Please check your email"); }, $scope.logError); }; } );