47 KiB
———————————————— angular.module('shiftworx'). directive('reportingSidebar', reportingSidebar);
function reportingSidebar() { // Runs during compile return { //name: '', // priority: 1, // terminal: true, scope: false, //{ /user: '=', software_key: '=', machineObj: '=',/ //}, // {} = isolate, true = child, false/undefined = no change controller: reportingSidebarCtrl, // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment // template: '
//}
}; }
reportingSidebarCtrl.$inject = ['$scope', '$element', '$attrs', '$transclude', '$http', '$location', '$route', '$filter', '$q', 'cr', '_', 'GlobalService'];
function reportingSidebarCtrl($scope, $element, $attrs, $transclude, $http, $location, $route, $filter, $q, cr, _, GlobalService) { $scope.disableInputs = false; $scope.cloudReportSelect = ''; $scope.applicationKey = 'custom-report'; $scope.shiftNumCounter = 1; $scope.dateDays = []; $scope.shiftAdditonCounter = 0; $scope.isThereData = false; $scope.isCountData = false; $scope.isTimerData = false; $scope.hardwareSelected = {}; $scope.hardCall = ''; $scope.showItems = true; $scope.shiftsComplete = [];
$scope.downloadReport = function() { alert('Placeholder for PDF download'); };
$scope.saveCloudReport = function() { if ($scope.reporting.xaxis === 'CustomDateRange') { alert('Saving a cloud report is not available on Custom Date Range...yet!') } else { // console.log($scope.reporting); //if ($scope.reporting.reportID === undefined) { $scope.cloudSave.push({ reportID: GlobalService.makeid(), reportName: $scope.reporting.reportName, machine: $scope.reporting.machineSelect, graphType: $scope.reporting.type, xaxis: $scope.reporting.xaxis, viewDataOptions: $scope.reporting.viewDataOption, startDate: $scope.reporting.startDate, endDate: $scope.reporting.endDate, yaxismax: $scope.reporting.yaxismax, input: $scope.reporting.hardware, shiftsEnabled: $scope.reporting.shiftsEnabled, }); $scope.reporting = { reportName: '', machineSelect: '', type: 'column', xaxis: 'Day', viewDataOption: '', startDate: '', endDate: '', yaxismax: false, hardware: '', shiftsEnabled: false };
postCloudReport($scope.applicationKey, GlobalService.getFactoryKey(), GlobalService.ngObjFixHack($scope.cloudSave));
}
};
$scope.deleteCloudSave = function(report) { if (report.reportID !== undefined) { angular.forEach($scope.cloudSave, function(value, key) { if (report.reportID === value.reportID) { var index = $scope.cloudSave.indexOf(value); //console.log(index); $scope.cloudSave.splice(index, 1); //console.log(index); postCloudReport($scope.applicationKey, GlobalService.getFactoryKey(), GlobalService.ngObjFixHack($scope.cloudSave)); } }); } else { alert('Load a report first!'); } };
$scope.loadCloudSave = function(cloudReport) { // console.log(cloudReport); $scope.reporting = { reportID: cloudReport.reportID, reportName: cloudReport.reportName, machineSelect: cloudReport.machine, type: cloudReport.graphType, xaxis: cloudReport.xaxis, viewDataOption: cloudReport.viewDataOptions, startDate: cloudReport.startDate, endDate: cloudReport.endDate, yaxismax: cloudReport.yaxismax, hardware: cloudReport.input, shiftsEnabled: cloudReport.shiftsEnabled, }; };
function postCloudReport(appKey, factoryKey, data) {
var dataObj = {
id: appKey,
factory: factoryKey,
data: data
};
//console.log(JSON.stringify(dataObj));
$.ajax({
url: 'http://54.213.13.56/api/app',
type: 'POST',
data: dataObj
}).done(function(data, statusText, xhr) {
console.log(data.message);
}).error(function(data, statusText, xhr) {
console.log(statusText);
});
}
$scope.graphType = 'column'; var self = this; $scope.reporting = { machineSelect: '', type: 'column', xaxis: 'Day', //yaxis: 'sum', yaxismax: undefined, startDate: '', endDate: '', dateMonthYear: '', dateDay: '', viewDataOption: 'count', shiftsEnabled: false, };
$scope.$watch("reporting.dateMonthYear", function(newValue, oldValue) { //$scope.machineDates = $scope.exporter.machineSelect.Dates; //console.log(newValue.date); if (newValue !== '') { var tempDateSplit = $scope.reporting.dateMonthYear.date.split(" "); //console.log('Year: ' + tempDateSplit[1]); $scope.splitYear = tempDateSplit[1]; //console.log('Month: ' + tempDateSplit[0]); $scope.splitMonth = tempDateSplit[0];
dateCreated = new Date(tempDateSplit[0] + ' 1, ' + tempDateSplit[1] + ' 00:00:00');
//newEndDate = new Date(newEndDate.getFullYear(), newEndDate.getMonth() + 1, 0);
endDaysDate = new Date(dateCreated.getFullYear(), dateCreated.getMonth() + 1, 0);
//endDaysDate.setDate(endDaysDate.getDate() + 1);
//console.log(endDaysDate.getDate());
for (var i = 1; i <= endDaysDate.getDate(); i++) {
$scope.dateDays.push(i);
}
}
});
$scope.options = { axes: { x: { key: 'x', type: 'date', zoomable: true }, y: { type: 'linear', max: $scope.maxyaxis }, y2: { type: 'linear', min: $scope.y2Max //max: $scope.maxyaxis } }, series: [{ y: undefined, color: 'steelblue', type: $scope.graphType, axis: 'y', striped: true, label: toTitleCase($scope.reportLabel + ' of ' + $scope.reporting.viewDataOption), id: "data" }, { y: undefined, //label: "Trendline", color: "#ff7f0e", type: "line", axis: "y", id: "trend", label: 'Average' }, { y: undefined, //label: "Trendline", color: "#006600", type: "line", axis: "y", id: "RegressionLine", label: 'Regression', visible: $scope.showItems, }], lineMode: 'linear', tension: 0.7, tooltip: { mode: 'scrubber', formatter: function(x, y, series) { //series.id['data ']= 'The Data: '; var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; if ($scope.reporting.xaxis === 'Month') { return monthNames[x.getMonth()] + ' ' + x.getFullYear() + ' - ' + series.label + ': ' + Math.round(y); } else { return x.toDateString() + ' - ' + series.label + ': ' + Math.round(y); } } }, drawLegend: $scope.showItems, drawDots: true, columnsHGap: 5 };
self.Initialise = function() { $scope.data = {}; $scope.blackout = false; $scope.cloudSave = []; $scope.machineObj = GlobalService.getMachineObj;
/* Fix This below to load dates dynamically for each machine when selected */
zeroOut();
//$scope.machineList = $rootScope.machineObj;
var trendType = 'trendCount';
var regressionLineType = 'countRegLine';
$scope.y2CountMax = 0;
$scope.y2TimerMax = 0;
$scope.y2Max = undefined;
grabAppData('shift-profile', GlobalService.getFactoryKey()).then(function(data) {
angular.forEach(data, function(items, key) {
//console.log(items.startTime * 1000);
if (isNaN(items.startTime * 1000)) {
items.startTime = new Date(items.startTime);
items.endTime = new Date(items.endTime);
} else {
items.startTime = new Date(items.startTime * 1000);
items.endTime = new Date(items.endTime * 1000);
}
});
$scope.shiftsObj = data;
//console.log(data.length);
//console.trace(cr.setupShiftVars(data.length));
cr.setupShiftVars(data.length);
$scope.numberOfShifts = data.length;
//cr.setupShiftVars($scope.numberOfShifts);
//console.log($scope.shiftsObj);
}, function(error) {
console.log('Failure...', error);
});
grabAppData($scope.applicationKey, GlobalService.getFactoryKey()).then(function(data) {
//console.log(data);
if (data.id === 'error') {
console.log(data);
} else {
$scope.cloudSave = data;
}
}, function(error) {
console.log('Failure...', error);
});
};
$scope.runReportWithSelection = function(item) { if (item !== '' || item !== undefined) { console.log(item); $scope.loadCloudSave(item); //$scope.changedVars(); } };
function getUserInfo(credentials) { var defer = $q.defer(); $http.get('http://54.213.13.56/api/user?username=' + credentials.username + '&password=' + credentials.password). success(function(data, status, headers, config) { defer.resolve(data); }). error(function(data, status, headers, config) { console.log('Error in userLogin: ' + data); }); return defer.promise; }
function grabAppData(appKey, factoryKey) { var defer = $q.defer(); $http.get('http://54.213.13.56/api/app/' + appKey + '/' + factoryKey). success(function(data) { //console.log(data); if (appKey === 'shift-profile') { angular.forEach(data, function(items, key) { angular.forEach(items.days, function(daySelected, day) { items.days[day] = daySelected == "true"; }); //console.log(data); angular.forEach(items.machines, function(machineSelected, machine) { items.machines[machine] = machineSelected == "true"; });
});
}
defer.resolve(data);
}).error(function(data) {
console.log('Error in grabAppData: ' + data);
});
return defer.promise;
}
$scope.$watch('factoryKey', function(newValue, oldValue, scope) { $scope.machineObj = GlobalService.getMachineObj; });
$scope.$watchGroup(["reporting.type", "reporting.viewDataOption", "reporting.yaxismax", "reporting.xaxis", "hardwareSelected"], function(newValues, oldValues) { //console.log(newValues[3]); $scope.y2Max = undefined;
if ($scope.reporting.viewDataOption === 'count') {
//$scope.y2Max = $scope.y2CountMax;
$scope.reportLabel = 'Sum';
} else {
//$scope.y2Max = $scope.y2TimerMax;
$scope.reportLabel = 'Percentage';
}
if ($scope.reporting.xaxis === 'Month') {
cr.setMonthOrDay('month');
} else {
cr.setMonthOrDay('day');
}
cr.setCountOrTimer($scope.reporting.viewDataOption);
if ($scope.reporting.viewDataOption === 'count') {
$scope.maxyaxis = undefined;
trendType = 'trendCount';
regressionLineType = 'countRegLine';
} else if ($scope.reporting.viewDataOption === 'timer') {
//console.log($scope.reporting.yaxismax);
if ($scope.reporting.yaxismax === true) {
$scope.maxyaxis = 100;
} else {
$scope.maxyaxis = undefined;
}
trendType = 'trendTimer';
regressionLineType = 'timerRegLine';
}
$scope.graphType = newValues[0];
$scope.options.axes.y.max = $scope.y2Max;
$scope.options.axes.y2.min = $scope.y2Max;
if ($scope.hardwareSelected.length === 1 || $scope.hardwareSelected.length === 0) {
$scope.options.series[0].y = $scope.reporting.viewDataOption;
$scope.options.series[0].type = $scope.graphType;
$scope.options.series[0].label = toTitleCase($scope.reportLabel + ' of ' + $scope.reporting.viewDataOption);
$scope.options.series[1].y = trendType;
$scope.options.series[2].y = regressionLineType;
$scope.options.series[2].visible = false;
} else {
for(i = 0; i < $scope.hardwareSelected.length; i++) {
$scope.options.series[i].y = $scope.reporting.viewDataOption;
$scope.options.series[i].type = $scope.graphType;
$scope.options.series[i].label = toTitleCase($scope.reportLabel + ' of ' + $scope.hardwareSelected[i].input);
}
}
$scope.options.axes.y.max = $scope.maxyaxis;
$scope.options.axes.y2.min = $scope.y2Max;
$scope.options.tooltip = {
mode: 'scrubber',
formatter: function(x, y, series) {
//series.id['data ']= 'The Data: ';
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
if ($scope.reporting.xaxis === 'Month') {
return monthNames[x.getMonth()] + ' ' +
x.getFullYear() + ' - ' +
series.label + ': ' + Math.round(y);
} else if ($scope.reporting.xaxis === 'Hourly') {
return formatAMPM(x) + ' ' +
' - ' + series.label + ': ' + Math.round(y);
} else {
return x.toDateString() + ' - ' +
series.label + ': ' + Math.round(y);
}
}
};
$scope.options.drawLegend = $scope.showItems;
var addItCount = 0;
var shiftNumber = 3;
if ($scope.reporting.shiftsEnabled === true) {
angular.forEach($scope.shiftsObj, function(value, key) {
// console.log($scope.options);
if (value.machines[$scope.reporting.machineSelect.Address]) {
$scope.options.series[shiftNumber].y = 'shift' + addItCount + $scope.reporting.viewDataOption;
$scope.options.series[shiftNumber].type = $scope.graphType;
$scope.options.series[shiftNumber].label = toTitleCase($scope.reportLabel + ' of ' + value.name);
shiftNumber++;
addItCount++;
}
//console.log();
//
});
}
});
function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }
function hexColorRandomizer() { var text = ""; var possible = "ABCDEF0123456789";
for (var i = 0; i < 6; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function toTitleCase(str) { return str.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }
$scope.$watch("reporting.machineSelect", function(newValue, oldValue) {
$scope.machineDates = $scope.reporting.machineSelect.Dates;
$scope.machineHardware = $scope.reporting.machineSelect.Hardware;
cr.setMachineName($scope.reporting.machineSelect.Name);
});
$scope.changedVars = function() { // if ($scope.options.series.length > 3) { // $scope.options.series.splice(3, $scope.options.series.length - 1); // } // $scope.shiftInfo = [];
$scope.yaxe = $scope.reporting.yaxis;
if ($scope.hardwareSelected.length > 0 && $scope.reporting.xaxis !== '' && $scope.reporting.machineSelect.Dates.length !== 0) {
$scope.data = [];
$scope.nonZeroData = [];
if ($scope.hardwareSelected.length === 1) {
cr.setHardware($scope.hardwareSelected[0].input);
// $scope.options.series[0].y = $scope.reporting.viewDataOption;
// $scope.options.series[0].type = $scope.graphType;
// $scope.options.series[0].label = toTitleCase($scope.reportLabel + ' of ' + $scope.reporting.viewDataOption);
// $scope.options.series[1].y = trendType;
// $scope.options.series[2].y = regressionLineType;
// $scope.options.series[2].visible = $scope.showItems;
}
if ($scope.reporting.xaxis === 'Day' || $scope.reporting.xaxis === 'Month') {
startDateSplit = $scope.reporting.startDate.date.split(' ');
endDateSplit = $scope.reporting.endDate.date.split(' ');
newStartDate = new Date(startDateSplit[0] + ' 1, ' + startDateSplit[1] + ' 00:00:00');
newEndDate = new Date(endDateSplit[0] + ' 1, ' + endDateSplit[1] + ' 00:00:00');
if (newEndDate.getMonth() === new Date().getMonth()) {
newEndDate = new Date();
} else {
//console.log($scope.reporting.startDate.date);
if ($scope.reporting.startDate.date === $scope.reporting.endDate.date && $scope.reporting.xaxis === 'Month') {
/*alert("Sorry you can't report on just one month with Month selected for time, " +
"I would suggest doing days if you want to complete this action");*/
//console.log('made it here');
newStartDate = new Date(startDateSplit[0] + ' 1, ' + startDateSplit[1] + ' 00:00:00');
newEndDate = new Date(endDateSplit[0] + ' 1, ' + endDateSplit[1] + ' 00:00:00');
//newEndDate = new Date(newEndDate.getFullYear(), newEndDate.getMonth() + 1, 0);
} else {
newEndDate = new Date(newEndDate.getFullYear(), newEndDate.getMonth() + 1, 0);
newEndDate.setDate(newEndDate.getDate() + 1);
}
}
} else {
if ($scope.reporting.xaxis === 'LastSeven') {
newEndDate = new Date();
newStartDate = new Date( /*newEndDate.getFullYear(), newEndDate.getMonth(), newEndDate.getDate(),0,0,0,0*/ );
newStartDate.setDate(newStartDate.getDate() - 7);
} else if ($scope.reporting.xaxis === 'LastWeek') {
newEndDate = new Date();
if (newEndDate.getDay() !== 0) {
newStartDate = new Date(newEndDate.setDate(newEndDate.getDate() - 7 - newEndDate.getDay()));
newEndDate.setDate(newStartDate.getDate() + 7);
// console.log(newStartDate);
} else {
newStartDate = new Date(newEndDate.setDate(newEndDate.getDate() - 7));
newEndDate.setDate(newStartDate.getDate() + 7);
}
//console.log(new Date(newEndDate));
} else if ($scope.reporting.xaxis === 'LastThirty') {
newEndDate = new Date();
newStartDate = new Date();
newStartDate.setDate(newStartDate.getDate() - 30);
} else if ($scope.reporting.xaxis === 'LastMonth') {
newStartDate = new Date();
newStartDate = new Date(newStartDate.getFullYear(), newStartDate.getMonth() - 1, 1, 0, 0, 0, 0);
//console.log(newStartDate);
newEndDate = new Date(newStartDate.getFullYear(), newStartDate.getMonth() + 1, 0, 0, 0, 0, 0);
//console.log(newEndDate);
/*newStartDate = new Date();
newStartDate.setDate(newStartDate.getMonth() - 1);*/
} else if ($scope.reporting.xaxis === 'LastNinty') {
newEndDate = new Date();
newStartDate = new Date();
newStartDate.setDate(newStartDate.getDate() - 90);
} else if ($scope.reporting.xaxis === 'Hourly') {
var tempDateSplit = $scope.reporting.dateMonthYear.date.split(" ");
//console.log('Year: ' + tempDateSplit[1]);
$scope.splitYear = tempDateSplit[1];
//console.log('Month: ' + tempDateSplit[0]);
$scope.splitMonth = tempDateSplit[0];
newStartDate = new Date(tempDateSplit[0] + ' ' + $scope.reporting.dateDay + ', ' + tempDateSplit[1] + ' 00:00:00');
newEndDate = new Date(tempDateSplit[0] + ' ' + $scope.reporting.dateDay + ', ' + tempDateSplit[1] + ' 23:59:59');
//console.log(newStartDate);
//console.log(newEndDate);
}
}
if ($scope.reporting.xaxis === 'CustomDateRange') {
cr.setStartDate(new Date($scope.reporting.dateRange.startDate).toDateString());
cr.setEndDate(new Date($scope.reporting.dateRange.endDate).toDateString());
} else {
cr.setStartDate(newStartDate.toDateString());
cr.setEndDate(newEndDate.toDateString());
}
$scope.disableInputs = true;
//$scope.test = newStartDate;
if ($scope.hardwareSelected.length === 1) {
$scope.options.series[2].visible = false;
$scope.options.drawLegend = false;
}
switch ($scope.reporting.xaxis) {
case 'Day':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'Month':
$scope.reporting.shiftsEnabled = false;
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
monthlyChart(newStartDate, newEndDate);
break;
case 'LastMonth':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'LastSeven':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'LastWeek':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'LastThirty':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'LastNinty':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
dailyChart(newStartDate, newEndDate);
break;
case 'Hourly':
$scope.data = [];
// $scope.options.series[2].visible = false;
// $scope.options.drawLegend = false;
$scope.nonZeroData = [];
hourlyChart(newStartDate, newEndDate);
break;
case 'CustomDateRange':
$scope.data = [];
$scope.nonZeroData = [];
dailyChart(new Date($scope.reporting.dateRange.startDate), new Date($scope.reporting.dateRange.endDate));
break;
default:
break;
}
} else {
alert('You need to fill in all fields first!');
}
};
function hourlyChart(startDate, endDate) { zeroOut(); processObj = 'deepsum-3600'; $scope.dateCount = 0; callHours(startDate, endDate, processObj); //$scope.disableInputs = false; }
function callHours(startDate, endDate, processObj) { d = startDate; da = endDate; if ($scope.hardwareSelected.length === 1) { webCall($scope.reporting.machineSelect.SoftwareKey, $scope.reporting.machineSelect.Address, processObj, Math.floor(new Date(d) / 1000), Math.floor(new Date(da) / 1000), $scope.hardwareSelected[0].input).then(function(data) { // console.log(data); dataHourlyAggregator(data, d, da); //$scope.disableInputs = false;
$scope.options.series[2].visible = true;
$scope.options.drawLegend = true;
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xCountCounter);
array_y.push($scope.data[i].count);
if ($scope.data[i].count > $scope.y2countmax) {
$scope.y2CountMax = $scope.data[i].count;
}
}
var countRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setCountSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(countRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].countRegLine = value;
tmpCount++;
}
});
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xTimerCounter);
array_y.push($scope.data[i].timer);
if ($scope.data[i].timer > $scope.y2TimerMax) {
$scope.y2TimerMax = $scope.data[i].timer;
}
}
var timerRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setTimeSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(timerRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].timerRegLine = value;
tmpCount++;
}
});
//console.log($scope.data);
$scope.disableInputs = false;
}, function(error) {
console.log('Failure...', error);
});
} else {
}
}
function dataHourlyAggregator(data, d, da) { //console.log(d); //console.log(da); var hourCounter = 1; angular.forEach(data.deepsum, function(value, key) { // console.log(value.count); // console.log(d); d.setHours(d.getHours() + 1);
// console.log($scope.reporting.machineSelect.PartCount);
if ($scope.reporting.machineSelect.PartCount !== undefined && $scope.reporting.machineSelect.PartCount !== '' && value.count !== 0) {
value.count = value.count / $scope.reporting.machineSelect.PartCount;
}
tempTimerData = value.timer / 3600 * 100;
//console.log(tempTimerData);
// }
//tempTimerData !== 0 &&
if ($scope.reporting.omitZeroes) {
if (tempTimerData !== 0 && value.count !== 0) {
$scope.isThereData = true;
} else {
$scope.isThereData = false;
}
} else {
if (tempTimerData !== 0 && value.count !== 0) {
$scope.isThereData = true;
}
}
/* else {
$scope.isThereData = false;
} */
if ($scope.isThereData === true) {
$scope.trendTimeData = trendLineCalculator(tempTimerData, $scope.timeCount, $scope.avgTimerData);
$scope.trendCountData = trendLineCalculator(value.count, $scope.countCount, $scope.accCountData);
$scope.accCountData += value.count;
var tempAvgCountData = $scope.accCountData / $scope.countCount;
$scope.avgTimerData += tempTimerData;
var tempAvgTimeData = ($scope.avgTimerData / $scope.timeCount);
cr.increaseAccCountKPI(value.count);
cr.increaseAccTimeKPI(Math.round(value.timer / 60 / 60));
cr.setAvgTimeKPI(tempAvgTimeData);
cr.setAvgCountKPI(tempAvgCountData);
$scope.countCount++;
$scope.timeCount++;
}
$scope.data.push({
x: new Date(d),
count: Math.round(value.count * 100) / 100,
timer: Math.round(tempTimerData * 100) / 100,
trendTimer: Math.round($scope.trendTimeData),
trendCount: Math.round($scope.trendCountData),
xCountCounter: $scope.countCount - 1,
xTimerCounter: $scope.timeCount - 1,
shifts: [],
});
});
//$scope.disableInputs = false;
// console.log($scope.data);
}
function dailyChart(startDate, endDate) { var daysOfYear = []; zeroOut(); processObj = 'sum'; $scope.dateCount = 0; var neverChangingEnd = endDate; var neverChangingStart = startDate; callDays(startDate, endDate);
}
function callDays(startDate, endDate) { d = startDate;
if (d < endDate) {
da = new Date(d);
da.setDate(da.getDate() + 1);
//processObj = '';
$scope.fullDay = (((24 * 60) * 60) * 1000);
$scope.WorkPeriod = ((($scope.reporting.machineSelect.WorkPeriod * 60) * 60) * 1000);
if ($scope.hardwareSelected.length === 1) {
webCall($scope.reporting.machineSelect.SoftwareKey, $scope.reporting.machineSelect.Address,
'sum', Math.floor(new Date(d) / 1000), Math.floor(new Date(da) / 1000),
$scope.hardwareSelected[0].input).then(function(data) {
dataAggregator(data, d, da);
d.setDate(d.getDate() + 1);
//console.log(ncStart + ' : ' + ncEnd);
callDays(d, endDate);
}, function(error) {
console.log('Failure...', error);
});
} else {
for (i = 0; i < $scope.hardwareSelected.length; i++) {
$scope.hardCall += '&index[]=' + $scope.hardwareSelected[i].input;
}
//console.log($scope.hardCall);
webMultiCall($scope.reporting.machineSelect.SoftwareKey, $scope.reporting.machineSelect.Address,
'sum', Math.floor(new Date(d) / 1000), Math.floor(new Date(da) / 1000),
$scope.hardCall).then(function(data) {
dataAggregator(data, d, da);
//console.log(data.length);
d.setDate(d.getDate() + 1);
$scope.hardCall = '';
//console.log(ncStart + ' : ' + ncEnd);
callDays(d, endDate);
}, function(error) {
console.log('Failure...', error);
});
}
} else {
//console.log($scope.data);
//console.log($scope.data);
//if ($scope.reporting.yaxis === 'sum') {
// create array_x & array_y
$scope.options.series[2].visible = false;
$scope.options.drawLegend = true;
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xCountCounter);
if ($scope.data[i].count !== 0) {
$scope.isCountData = true;
}
array_y.push($scope.data[i].count);
if ($scope.data[i].count > $scope.y2countmax) {
$scope.y2CountMax = $scope.data[i].count;
}
}
if ($scope.isCountData === true) {
var countRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setCountSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
} else {
var countRegLine = 0;
cr.setCountSlopeKPI(0);
}
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(countRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].countRegLine = value;
tmpCount++;
}
});
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xTimerCounter);
// console.log($scope.data[i].timer);
if ($scope.data[i].timer !== 0) {
$scope.isTimerData = true;
}
array_y.push($scope.data[i].timer);
if ($scope.data[i].timer > $scope.y2TimerMax) {
$scope.y2TimerMax = $scope.data[i].timer;
}
}
if ($scope.isTimerData === true) {
var timerRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setTimeSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
} else {
var timerRegLine = 0;
cr.setTimeSlopeKPI(0);
}
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(timerRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].timerRegLine = value;
tmpCount++;
}
});
//console.log($scope.data);
$scope.disableInputs = false;
}
}
function zeroOutShifts() {
$scope.shiftCounter = 1;
$scope.shiftNumberCounter = 1;
$scope.trendShiftTimeData = 0;
$scope.trendShiftCountData = 0;
$scope.accumShiftTimerData = 0;
$scope.avgShiftTimerData = 0;
}
var within_std_of = 2;
average = function(a) { var r = { mean: 0, variance: 0, deviation: 0 }, t = a.length; for (var m, s = 0, l = t; l--; s += a[l]); for (m = r.mean = s / t, l = t, s = 0; l--; s += Math.pow(a[l] - m, 2)); return r.deviation = Math.sqrt(r.variance = s / t), r; };
withinStd = function(mean, val, stdev) { var low = mean - (stdev * x.deviation); var hi = mean + (stdev * x.deviation); return (val > low) && (val < hi); };
function monthlyChart(startDate, endDate) { //console.log('Monthly was called'); var daysOfYear = []; d = startDate; zeroOut(); processObj = 'sum';
nextMonth(startDate, endDate, processObj);
}
function nextMonth(startDate, endDate, processObj) { if (d <= endDate) { $scope.WorkPeriod = ((($scope.reporting.machineSelect.WorkPeriod * 60) * 60) * 1000); if (d === endDate) { da = new Date(d); da = new Date(da.getFullYear(), da.getMonth() + 1, 0);
//da.setMonth(da.getMonth() + 1);
if ($scope.hardwareSelected.length === 1) {
webCall($scope.reporting.machineSelect.SoftwareKey, $scope.reporting.machineSelect.Address,
processObj, Math.floor(new Date(d) / 1000), Math.floor(new Date(da) / 1000),
$scope.hardwareSelected[0].input).then(function(data) {
/*console.log(Math.floor(new Date(d) / 1000));
console.log(Math.floor(new Date(da) / 1000));*/
dataAggregator(data, d, da);
//d.setMonth(d.getMonth() + 1);
//nextMonth(startDate, endDate, processObj);
});
} else {
}
} else {
da = new Date(d);
da.setMonth(da.getMonth() + 1);
webCall($scope.reporting.machineSelect.SoftwareKey, $scope.reporting.machineSelect.Address,
processObj, Math.floor(new Date(d) / 1000), Math.floor(new Date(da) / 1000),
$scope.reporting.hardware).then(function(data) {
/*console.log(Math.floor(new Date(d) / 1000));
console.log(Math.floor(new Date(da) / 1000));*/
dataAggregator(data, d, da);
d.setMonth(d.getMonth() + 1);
nextMonth(startDate, endDate, processObj);
});
}
} else {
// $rootScope.countSlope = 0;
// $rootScope.timeSlope = 0;
if ($scope.reporting.xaxis === 'Month') {
$scope.options.series[2].visible = false;
$scope.options.drawLegend = false;
} else {
$scope.options.series[2].visible = true;
$scope.options.drawLegend = true;
}
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xCountCounter);
array_y.push($scope.data[i].count);
if ($scope.data[i].count > $scope.y2CountMax) {
$scope.y2CountMax = $scope.data[i].count;
}
}
var countRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setCountSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(countRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].countRegLine = value;
tmpCount++;
}
});
array_x = [];
array_y = [];
for (i = 0; i < $scope.data.length; ++i) {
array_x.push($scope.data[i].xTimerCounter);
array_y.push($scope.data[i].timer);
if ($scope.data[i].timer > $scope.y2TimerMax) {
$scope.y2TimerMax = $scope.data[i].timer;
}
}
var timerRegLine = findLineByLeastSquares(array_x, array_y); //findLineByLeastSquaresLog(array_x, array_y);
//findLineByLeastSquaresLog(array_x, array_y);
cr.setTimeSlopeKPI(Math.round($scope.tempSlope * 10) / 10) /* * 100*/ ;
//console.log(countRegLine);
tmpCount = 0;
angular.forEach(timerRegLine[1], function(value, key) {
if (tmpCount !== countRegLine[1].length) {
$scope.data[tmpCount].timerRegLine = value;
tmpCount++;
}
});
$scope.disableInputs = false;
}
}
function zeroOut() { $scope.shiftNumCounter = 1; $scope.countCount = 1; $scope.timeCount = 1; $scope.shiftCounter = 1; $scope.shiftNumberCounter = 1; $scope.trendTimeData = 0; $scope.trendCountData = 0; cr.resetCustomReportKPIs(); cr.setupShiftVars($scope.numberOfShifts); $scope.avgTimerData = 0; // $rootScope.rootAccTimeData = $scope.accTimeData = 0; $scope.accCountData = 0; // $rootScope.rootAvgTimeData = $scope.avgTimeData = 0; // $rootScope.rootAvgCountData = $scope.avgCountData = 0; $scope.avgTimerData = 0; $scope.isThereData = false; // $rootScope.timeSlope = 0; // $rootScope.countSlope = 0; $scope.shiftCountDataTotal = 0; $scope.shiftTimerDataTotal = 0; $scope.shiftAdditonCounter = 0; $scope.accShiftTimeData = 0; $scope.accShiftCountData = 0; /$rootScope.machinesName = ''; $rootScope.startingDate = ''; $rootScope.endingDate = '';/
}
function getCloudReportInfo() { var defer = $q.defer(); $http.get('http://54.213.13.56/api/app/' + appKey + '/' + factoryKey). success(function(data) { //console.log(data[data.length].id); defer.resolve(data); }).error(function(data) { console.log('Error in getCloudReportInfo: ' + data); }); return defer.promise; }
function webCall(softwareKey, address, processObj, startDate, endDate, hardware) { var defer = $q.defer(); // console.log('http://54.213.13.56/api/' + softwareKey + '/' + address + // '?process[]=' + processObj + '&date[]=' + startDate + '&date[]=' + endDate + '&index=' + // hardware); $http.get('http://54.213.13.56/api/' + softwareKey + '/' + address + '?process[]=' + processObj + '&date[]=' + startDate + '&date[]=' + endDate + '&index=' + hardware). success(function(data) { //console.log('Data: ' + data); defer.resolve(data); }). error(function(data) { alert(data); }); return defer.promise; }
function webMultiCall(softwareKey, address, processObj, startDate, endDate, hardware) { var defer = $q.defer(); // console.log('http://54.213.13.56/api/' + softwareKey + '/' + address + // '?process[]=' + processObj + '&date[]=' + startDate + '&date[]=' + endDate + hardware); $http.get('http://54.213.13.56/api/' + softwareKey + '/' + address + '?process[]=' + processObj + '&date[]=' + startDate + '&date[]=' + endDate + hardware). success(function(data) { //console.log('Data: ' + data); defer.resolve(data); }). error(function(data) { alert(data); }); return defer.promise; }
function dataAggregator(data, d, da) { //console.log($scope.reporting.machineSelect.PartCount); if ($scope.hardwareSelected.length === 1) {
if ($scope.reporting.machineSelect.PartCount !== undefined && $scope.reporting.machineSelect.PartCount !== '' && data.sum.count !== 0) {
data.sum.count = data.sum.count / $scope.reporting.machineSelect.PartCount;
}
if ($scope.reporting.xaxis === 'Month') {
tempDate = d;
tempDate = new Date(tempDate.getFullYear(), tempDate.getMonth() + 1, 0);
tempDate.setDate(tempDate.getDate());
//console.log(tempDate.getDate());
tempTimerData = data.sum.timer / ((tempDate.getDate() * $scope.WorkPeriod) / 1000) * 100;
} else if ($scope.WorkPeriod !== undefined) {
tempTimerData = data.sum.timer / (($scope.WorkPeriod) / 1000) * 100;
/*console.log('Timer: ' + data.sum.timer);
console.log('Work Period: ' + $scope.WorkPeriod);
console.log('Initial Work Period: ' + $scope.reporting.machineSelect.WorkPeriod);
console.log('Calculations: ' + data.sum.timer / (($scope.WorkPeriod) / 1000) * 100);*/
} else {
tempTimerData = data.sum.timer / ((da / d) / 1000) * 100;
}
// console.log(tempTimerData);
// console.log(data.sum.count);
if ($scope.reporting.omitZeroes === true) {
if (tempTimerData !== 0 && data.sum.count !== 0) {
$scope.isThereData = true;
} else {
$scope.isThereData = false;
}
} else {
if (tempTimerData !== 0 && data.sum.count !== 0) {
$scope.isThereData = true;
}
}
/* else {
$scope.isThereData = false;
} */
//var trendCountData = 0;
//console.log('Temp Timer data after calc: ' + data.sum.timer);
if ($scope.isThereData === true) {
// console.log(tempTimerData);
// console.log(data.sum.count);
$scope.trendTimeData = trendLineCalculator(tempTimerData, $scope.timeCount, $scope.avgTimerData);
$scope.trendCountData = trendLineCalculator(data.sum.count, $scope.countCount, $scope.accCountData);
$scope.accCountData += data.sum.count;
var tempAvgCountData = $scope.accCountData / $scope.countCount;
$scope.avgTimerData += tempTimerData;
var tempAvgTimeData = ($scope.avgTimerData / $scope.timeCount);
cr.increaseAccCountKPI(data.sum.count);
cr.increaseAccTimeKPI(Math.round(data.sum.timer / 60 / 60));
cr.setAvgTimeKPI(tempAvgTimeData);
cr.setAvgCountKPI(tempAvgCountData);
$scope.countCount++;
$scope.timeCount++;
}
$scope.data.push({
x: new Date(d),
count: Math.round(data.sum.count * 100) / 100,
timer: Math.round(tempTimerData * 100) / 100,
trendTimer: Math.round($scope.trendTimeData),
trendCount: Math.round($scope.trendCountData),
xCountCounter: $scope.countCount - 1,
xTimerCounter: $scope.timeCount - 1,
shifts: [],
});
} else {
//console.log(_.size(data));
console.log(data);
console.log($scope.hardwareSelected);
}
}
function trendLineCalculator(value, count, accValue) { // console.log('value: ' + value); // console.log('count: ' + count); // console.log('accValue: ' + accValue);
average = (accValue + value) / count;
//console.log('After Claculations and Such: ' + average);
return average;
}
$scope.changedMachine = function(item) {
$scope.machineDates = item.Dates;
//console.log(item);
};
/**
- Write to the Console
- @param {string} message */ self.log = function(message) { console.log(message); };
function findLineByLeastSquares(values_x, values_y) { var sum_x = 0; var sum_y = 0; var sum_xy = 0; var sum_xx = 0; var count = 0;
/*
* We'll use those variables for faster read/write access.
*/
var x = 0;
var y = 0;
/*****************************WHAT MARKO ADDED***************************************/
//index of array where y array will progress into a sequence of non-zero elements
var index_nonZero;
//first if statement checks if first element is zero
//if y[0]!=0 then we have nothing to worry about
//if y[0] = 0 then we see where the elements begin to be non zero
//once we find that spot, we break out of loop and remove beginning elements that are zero.
if (values_y[0] === 0) {
for (i = 0; i < values_y.length; i++) {
if (values_y[i] !== 0) {
index_nonZero = i;
break;
}
}
}
values_y = values_y.splice(index_nonZero, values_y.length);
//tempValuesX = values_x.splice(0, index_nonZero);
values_x = values_x.splice(index_nonZero, values_x.length);
// console.log(values_y);
//console.log(values_X);
/******************************END OF WHAT MARKO ADDED***************************/
var values_length = values_x.length;
if (values_length != values_y.length) {
throw new Error('The parameters values_x and values_y need to have same size!');
}
/*
* Nothing to do.
*/
if (values_length === 0) {
return [
[],
[]
];
}
// values_y is shorter than x and so it fails trying to do calculations below. Need to
// look into for a fix
/*
* Calculate the sum for each of the parts necessary.
*/
for (var v = 0; v < values_length; v++) {
x = values_x[v];
y = values_y[v];
sum_x += x;
if (y !== 0) {
sum_y += y;
} else {
sum_y += 0;
}
sum_xx += x * x;
sum_xy += x * y;
count++;
}
/*
* Calculate m and b for the formular:
* y = x * m + b
*/
var m = (count * sum_xy - sum_x * sum_y) / (count * sum_xx - sum_x * sum_x);
$scope.tempSlope = m;
var b = (sum_y / count) - (m * sum_x) / count;
/*
* We will make the x and y result line now
*/
var result_values_x = [];
var result_values_y = [];
for (i = 0; i < index_nonZero; i++) {
result_values_y.push(0);
result_values_x.push(0);
}
for (var v = 0; v < values_length; v++) {
x = values_x[v];
y = x * m + b;
result_values_x.push(x);
result_values_y.push(y);
}
return [result_values_x, result_values_y];
}
$scope.selectedHardware = function() { $scope.hardwareSelected = $filter('filter')($scope.machineHardware, { checked: true }); }
$scope.$watch('hardwareSelected', function(newValue, oldValue) { if(_.size(newValue) > 1){ $scope.options.series = []; for(i = 0; i < $scope.hardwareSelected.length; i++) { $scope.options.series.push({ y: 'shift', // - $scope.reporting.viewDataOption, color: '#0000FF', type: $scope.graphType, axis: 'y', striped: true, label: toTitleCase($scope.reportLabel + ' of ' + $scope.hardwareSelected[i].input), //id: value.id }); // $scope.options.series.push({ // y: 'shift', // - $scope.reporting.viewDataOption, // color: '#0000FF', // type: $scope.graphType, // axis: 'y', // striped: true, // label: toTitleCase('Average of ' + $scope.hardwareSelected[i].input), // //id: value.id // }); }
} else {
$scope.options.series = [{
y: undefined,
color: 'steelblue',
type: $scope.graphType,
axis: 'y',
striped: true,
label: toTitleCase($scope.reportLabel + ' of ' + $scope.reporting.viewDataOption),
id: "data"
}, {
y: undefined,
//label: "Trendline",
color: "#ff7f0e",
type: "line",
axis: "y",
id: "trend",
label: 'Average'
}, {
y: undefined,
//label: "Trendline",
color: "#006600",
type: "line",
axis: "y",
id: "RegressionLine",
label: 'Regression',
visible: $scope.showItems,
}];
}
}); // Initialise Directive self.Initialise(); }