demo20230512/Browser_Local/js/LCA/DetailSurveyForm/LCAWorkHourController.js
2023-05-12 10:20:28 +08:00

634 lines
26 KiB
JavaScript

/*
** Views/Partial/LCA/WorkHour.cshtml is using this controller
*/
angular.module('CarbonFootprint')
.controller('LCAWorkHourCtrl', ['$q', '$scope', '$http', '$routeParams', 'ParameterCacheService', 'LCADetailCacheService', 'DATE_CONSTANTS', 'UploadFile', 'MultiLanguageService', 'ExportCsvService',
function ($q, $scope, $http, $routeParams, ParameterCacheService, LCADetailCacheService, DATE_CONSTANTS, UploadFile, MultiLanguageService, ExportCsvService) {
// Multi-language resource object
var Resource;
// this property controlls modal form , will be passed to table-edit-modal directive
$scope.modalFormOption = {};
$scope.Editable = false;
$scope.dataQualityOption = {};
$scope.dataQualityOption.data = {};
$scope.newPeopleType = "";
$scope.selectedPeopleType = "直接人員";
$scope.peopleTypes = ["直接人員", "間接人員" ];
$scope.onPeopleTypeChange = function () {
console.log('onPeopleTypeChange', $scope.selectedPeopleType);
getAllDataAsync($routeParams.LCAID, $scope.selectedPeopleType).then(function (data) {
$scope.processWorkHoursData(data);
})
};
$scope.createPeopleType = function () {
if ($scope.newPeopleType.trim() == "") {
return;
}
$http.post($scope.baseUrl + '/api/WorkHour/CreatePeopleTypes', { LCAID: $routeParams.LCAID, peopleType: $scope.newPeopleType}
).success(function (data) {
$scope.peopleTypes = data.PeopleTypes;
getPeopleTypes($scope.newPeopleType);
$scope.selectedPeopleType = $scope.newPeopleType;
$scope.newPeopleType = "";
getAllDataAsync($routeParams.LCAID, $scope.selectedPeopleType).then(function (data) {
$scope.processWorkHoursData(data);
})
}).error(function (data, status) {
alert(data.ExceptionMessage);
});
};
$scope.deletePeopleType = function () {
if ($scope.selectedPeopleType == "直接人員" || $scope.selectedPeopleType == "間接人員") {
alert("無法刪除預設人員");
return;
}
$http.post($scope.baseUrl + '/api/WorkHour/DeletePeopleTypes', { LCAID: $routeParams.LCAID, peopleType: $scope.selectedPeopleType }
).success(function (data) {
$scope.peopleTypes = data.PeopleTypes;
getPeopleTypes(data.PeopleTypes[0]);
$scope.selectedPeopleType = data.PeopleTypes[0];
getAllDataAsync($routeParams.LCAID, $scope.selectedPeopleType).then(function (data) {
$scope.processWorkHoursData(data);
})
}).error(function (data, status) {
alert(data.ExceptionMessage);
});
};
function getPeopleTypes (selectedPeopleType = null) {
$http.get($scope.baseUrl + '/api/WorkHour/GetPeopleTypes/' + $routeParams.LCAID
).success(function (data) {
$scope.peopleTypes = data.PeopleTypes;
if (selectedPeopleType != null) {
$scope.selectedPeopleType = selectedPeopleType;
}
}).error(function (data, status) {
alert(data.ExceptionMessage);
});
}
getPeopleTypes();
// set $scope.baseUrl
var baseUrl = $scope.baseUrl;
if (typeof (baseUrl) === 'undefined' || baseUrl == null) {
var arr = window.location.href.split("/");
if (arr[3].indexOf('app') == 0)
baseUrl = '';
else
baseUrl = '/' + arr[3];
$scope.baseUrl = baseUrl;
}
$scope.updateRow = function (row) {
if (typeof (row.newWorkerNumber) === 'undefined' || row.newWorkerNumber <= 0)
return;
if (typeof (row.newWorkDay) === 'undefined' || row.newWorkDay <= 0)
return;
if (typeof (row.newAverageHourPerDay) === 'undefined' || row.newAverageHourPerDay <= 0)
return;
row.Scalar = row.newWorkerNumber * row.newWorkDay * row.newAverageHourPerDay;
//console.log('updateRow', row);
};
/* modelBuilder for create & export */
$scope.modelBuilder = {
create: function (data, LCAID) {
try {
// check Type
var typeID;
var typeName = data[1];
var WorkHourPeopleType = undefined;
if (typeName == Resource['DirectStaff'])
typeID = 0;
else if (typeName == Resource['IndirectStaff'])
typeID = 1;
else {
typeID = 2;
WorkHourPeopleType = typeName;
}
var model = {
// importing only depends on the order of data, not month
Type: typeID,
WorkerNumber: parseFloat(data[2]) ? data[2] : 0,
WorkDay: parseFloat(data[3]) ? data[3] : 0,
AverageHourPerDay: parseFloat(data[4]) ? data[4] : 0,
Description: data[5],
WorkHourPeopleType: WorkHourPeopleType,
LCAID: LCAID
};
model.Scalar = parseFloat(model.WorkerNumber) * parseFloat(model.WorkDay) * parseFloat(model.AverageHourPerDay)
console.log(data.length)
console.log(getObjectSize(model))
if (data.length !== getObjectSize(model) - 2)
throw Resource['EXCELFileFormatWrong'];
// if find incorrect Type
if (model.Type === undefined)
throw Resource['DirectStaff'] + '/' + Resource['IndirectStaff'] + ' Error';
return model;
}
catch (err) {
return { error: err };
}
},
export: function (list) {
$http.get($scope.baseUrl + '/api/WorkHour/GetAllWorkHours/' + $routeParams.LCAID)
.success(function (response) {
var workHours = response.WorkHours;
var startDate = new Date($scope.lcaDetail.StartDate);
var endDate = new Date($scope.lcaDetail.EndDate);
// 將起訖日期改為同年第一與最後一天
startDate.setMonth(0, 1);
endDate.setMonth(11, 31);
var currentDate = startDate;
var directIndex = 0;
for (var i = 0; i < workHours.length; i++) {
var currentMonth = DATE_CONSTANTS.months[(workHours[i].Index-1) % 12];
var currentYear = currentDate.getFullYear() + parseInt(workHours[i].Index / 12);
workHours[directIndex].Month = currentMonth;
workHours[directIndex++].showYear = currentYear;
}
var data = [];
// header
data.push([Resource['StaticLabelGlobal_Month'],
Resource['DirectStaff'] + '/' + Resource['IndirectStaff'],
Resource['WorkerNumber'],
Resource['WorkDays'],
Resource['AverageHourPerDay'],
Resource['DescriptionAndExplanation'] + Resource['StaticLabelEvidenceOfElectronicFileDescription']]);
// body
angular.forEach(workHours, function (entry) {
var csv = [];
//column 1
csv.push(entry.Month);
//column 2
if (entry.Type == 0)
csv.push(Resource['DirectStaff']);
else if (entry.Type == 1)
csv.push(Resource['IndirectStaff']);
else
csv.push(entry.WorkHourPeopleType);
//column 3
csv.push(entry.WorkerNumber);
//column 4
csv.push(entry.WorkDay);
//column 5
csv.push(entry.AverageHourPerDay);
//column 6
csv.push(entry.Description);
data.push(csv);
})
ExportCsvService.startExport(data, "Export_WorkHour.csv");
})
}
}
/* file import options & modal control */
$scope.fileImportOptions = {
modelBuilder: $scope.modelBuilder,
saveAsync: batchCreateAndUpdateCacheAllTypes
};
$scope.fileImportModal = {
show: false
}
/* quote options & modal control */
$scope.quoteOptions = {
queryDataAsyncFn: function (LCAID) {
var deferred = $q.defer();
$http.get($scope.baseUrl + '/api/WorkHour/GetAllWorkHours/' + LCAID)
.success(function (data) {
deferred.resolve(data.WorkHours);
})
return deferred.promise;
},
saveAsyncFn: batchCreateAndUpdateCacheAllTypes
}
$scope.quoteModal = {
show: false
}
// Sync 'ParameterID' based on 'Source', because ngModel of <select> is bind to 'Source'
$scope.$watch('selectRow.toBeEdit.Source', function (newValue) {
angular.forEach($scope.sources, function (value, key) {
if (value === newValue) {
$scope.selectRow.toBeEdit.ParameterID = key;
}
});
}, true);
$scope.processWorkHoursData = function (response){
var lcaDetail = response[0];
var workHours = response[1].data.WorkHours;
var sheetHeader = response[1].data.SheetHeader ? response[1].data.SheetHeader : {};
//console.log('response[1].data', response[1].data);
$scope.Factors = response[1].data.Factors;
//console.log('$scope.Factors', $scope.Factors);
var startDate = new Date(lcaDetail.StartDate);
var endDate = new Date(lcaDetail.EndDate);
// 將起訖日期改為同年第一與最後一天
startDate.setMonth(0, 1);
endDate.setMonth(11, 31);
// prepare row data
// Direct and Indirect labor
var directWorkHoursModel = [];
//var indirectWorkHoursModel = [];
var currentDate = startDate;
var directIndex = 0;
//var indirectIndex = 0;
var i = 0;
while ((workHours.length - i - 1) >= 0) {
if (workHours.length > 0) {
var row = workHours[workHours.length - i - 1];
row['oldScalar'] = row.Scalar;
//if (row.Type === 0) {
// direct labor
directWorkHoursModel[directIndex++] = row;
//}
//else {
// Type == 1, indirect labor
// indirectWorkHoursModel[indirectIndex++] = row;
//}
}
i++;
}
var directIndex = 0;
//var indirectIndex = 0;
while (currentDate < endDate) {
var currentMonth = DATE_CONSTANTS.months[currentDate.getMonth()];
var currentYear = currentDate.getFullYear();
if ((directWorkHoursModel.length - directIndex - 1) >= 0) {
directWorkHoursModel[directIndex].Month = currentMonth;
directWorkHoursModel[directIndex++].showYear = currentYear;
}
else {
directWorkHoursModel[directIndex++] = {
ID: 0,
Index: directIndex,
Month: currentMonth,
showYear: currentYear,
WorkerNumber: 0,
WorkDay: 0,
AverageHourPerDay: 0,
Type: 0,
ProportionOfWorkingHours: 0,
Scalar: 0,
LCAID: $routeParams.LCAID,
KgCO2e: 0,
Description: ""
};
}
/*if ((indirectWorkHoursModel.length - indirectIndex - 1) >= 0) {
indirectWorkHoursModel[indirectIndex].Month = currentMonth;
indirectWorkHoursModel[indirectIndex++].showYear = currentYear;
}
else {
indirectWorkHoursModel[indirectIndex++] = {
ID: 0,
Index: indirectIndex,
Month: currentMonth,
showYear: currentYear,
WorkerNumber: 0,
WorkDay: 0,
AverageHourPerDay: 0,
Type: 1,
ProportionOfWorkingHours: 0,
Scalar: 0,
LCAID: $routeParams.LCAID,
KgCO2e: 0,
Description: ""
};
}*/
currentDate.setMonth(currentDate.getMonth() + 1);
}
$scope.modelDirectWorkHours = directWorkHoursModel;
//$scope.modelIndirectWorkHours = indirectWorkHoursModel;
calculateDirectSum();
//calculateIndirectSum();
// $scope.sheetHeader is parent's object
$scope.sheetHeader.SheetFillerName = sheetHeader.SheetFillerName;
$scope.sheetHeader.Phone = sheetHeader.Phone;
$scope.sheetHeader.Department = sheetHeader.Department;
}
$scope.getAllWorkHoursData = function () {
}
// Get data and prepare $scope.model
getAllDataAsync($routeParams.LCAID, null)
.then(function (response) {
$scope.processWorkHoursData(response);
}, function (error) {
console.log(error);
});
// Get the lca status
LCADetailCacheService.getLCADetailAsync($routeParams.LCAID)
.then(function (lcaDetail) {
// int 0, 1, 2, 3, 4
$scope.lcaStatus = lcaDetail.Status;
$scope.dataQualityOption.showSaveBtn = lcaDetail.Status == 1;
// $scope.modalFormOption.editable = $scope.lcaStatus == 0;
}, function (error) {
console.log(error);
});
// Get multilanguage resource
MultiLanguageService.getResourceAsync()
.then(function (resource) {
Resource = resource;
}, function (error) {
console.log(error);
});
/**
* Private function: save all async
* @param {[Array]} : array of parsed objects
* @return {[promise]}
*/
function batchCreateAndUpdateCache(parsedList) {
var deferred = $q.defer();
//var directWorkHoursModel = [];
//var indirectWorkHoursModel = [];
//var directIndex = 0;
//var indirectIndex = 0;
//// group and set index
//for (var i in parsedList) {
// if (parsedList[i].Type == 0 && directIndex < $scope.modelDirectWorkHours.length) {
// directIndex++;
// parsedList[i].Index = directIndex;
// directWorkHoursModel.push(parsedList[i]);
// }
// else if (parsedList[i].Type == 1 && indirectIndex < $scope.modelIndirectWorkHours.length) {
// indirectIndex++;
// parsedList[i].Index = indirectIndex;
// indirectWorkHoursModel.push(parsedList[i]);
// }
//}
//// remove redundant content
//parsedList = directWorkHoursModel.concat(indirectWorkHoursModel);
// sava all
$http.post($scope.baseUrl+'/api/WorkHour/SaveWorkHours/', parsedList)
.success(function (data) {
// close modals
$scope.fileImportModal.show = false;
$scope.quoteModal.show = false;
// group by Type
var directWorkHoursModel = [];
var indirectWorkHoursModel = [];
angular.forEach(data.result, function (item) {
if (item.Type == 0)
directWorkHoursModel.push(item);
else
indirectWorkHoursModel.push(item);
})
// update $scope.modelDirectWorkHours
for (var i = 0; i < $scope.modelDirectWorkHours.length; i++) {
var item = $scope.modelDirectWorkHours[i];
if (directWorkHoursModel[i]) {
item.WorkerNumber = directWorkHoursModel[i].WorkerNumber;
item.WorkDay = directWorkHoursModel[i].WorkDay;
item.AverageHourPerDay = directWorkHoursModel[i].AverageHourPerDay;
item.Scalar = directWorkHoursModel[i].Scalar;
item.Description = directWorkHoursModel[i].Description;
}
else {
item.WorkerNumber = 0;
item.WorkDay = 0;
item.AverageHourPerDay = 0;
item.Scalar = 0;
}
}
// update $scope.modelIndirectWorkHours
for (var i = 0; i < $scope.modelIndirectWorkHours.length; i++) {
var item = $scope.modelIndirectWorkHours[i];
if (indirectWorkHoursModel[i]) {
item.WorkerNumber = indirectWorkHoursModel[i].WorkerNumber;
item.WorkDay = indirectWorkHoursModel[i].WorkDay;
item.AverageHourPerDay = indirectWorkHoursModel[i].AverageHourPerDay;
item.Scalar = indirectWorkHoursModel[i].Scalar;
item.Description = indirectWorkHoursModel[i].Description;
}
else {
item.WorkerNumber = 0;
item.WorkDay = 0;
item.AverageHourPerDay = 0;
item.Scalar = 0;
}
}
calculateDirectSum();
//calculateIndirectSum();
deferred.resolve(data);
})
.error(function (e) {
console.log(e.Message);
})
return deferred.promise;
}
function batchCreateAndUpdateCacheAllTypes(parsedList) {
var deferred = $q.defer();
// sava all
$http.post($scope.baseUrl + '/api/WorkHour/SaveAllTypesWorkHours/', parsedList)
.success(function (data) {
$scope.fileImportModal.show = false;
$scope.quoteModal.show = false;
$scope.peopleTypes = data.PeopleTypes;
if ($scope.peopleTypes.indexOf($scope.selectedPeopleType) == -1)
$scope.selectedPeopleType = '直接人員';
$scope.onPeopleTypeChange($scope.selectedPeopleType);
deferred.resolve(data);
})
.error(function (e) {
console.log(e.Message);
})
return deferred.promise;
}
/**
* Get all list data from server
* @param {[Int]} : LCAID
* @return {[promise]}
*/
function getAllDataAsync(LCAID, peopleType=null) {
var deferred = $q.defer();
$q.all([LCADetailCacheService.getLCADetailAsync(LCAID),
$http.post($scope.baseUrl + '/api/WorkHour/GetWorkHours', { LCAID: LCAID, peopleType: peopleType })])
.then(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
//$scope.uploadFile = function (rowIndex) {
// UploadFile.uploadFile($scope, $scope.model[rowIndex]);
//};
//$scope.downloadFile = function (fileUrl) {
// UploadFile.downloadFile(fileUrl);
//};
// Note: must calculate direct and indirect labor
function calculateDirectSum() {
var sumWorkDay = 0;
var sumStaffTotalWorkHour = 0;
var sumKgCO2e = 0;
angular.forEach($scope.modelDirectWorkHours, function (item) {
sumWorkDay += item.sumWorkDay;
sumStaffTotalWorkHour += item.Scalar;
sumKgCO2e += item.KgCO2e;
item.ProportionOfWorkingHours = item.AverageHourPerDay / 8;
});
$scope.sumWorkDay = sumWorkDay;
$scope.sumStaffTotalWorkHour = sumStaffTotalWorkHour;
$scope.sumKgCO2e = sumKgCO2e;
}
function calculateIndirectSum() {
var sumWorkDay = 0;
var sumStaffTotalWorkHour = 0;
var sumKgCO2e = 0;
angular.forEach($scope.modelIndirectWorkHours, function (item) {
sumWorkDay += item.sumWorkDay;
sumStaffTotalWorkHour += item.Scalar;
sumKgCO2e += item.KgCO2e;
item.ProportionOfWorkingHours = item.AverageHourPerDay / 8;
});
$scope.sumIndirectWorkDay = sumWorkDay;
$scope.sumIndirectStaffTotalWorkHour = sumStaffTotalWorkHour;
$scope.sumIndirectKgCO2e = sumKgCO2e;
}
$scope.saveData = function () {
$scope.Editable = false;
var modelWorkHour = [];
angular.forEach($scope.modelDirectWorkHours, function (item) {
item.WorkerNumber = item.newWorkerNumber;
item.WorkDay = item.newWorkDay;
item.AverageHourPerDay = item.newAverageHourPerDay;
if (item.oldScalar == item.Scalar) {
item.Scalar = item.WorkerNumber * item.WorkDay * item.AverageHourPerDay;
}
item.Description = item.newDescription;
modelWorkHour.push(item);
});
angular.forEach($scope.modelIndirectWorkHours, function (item) {
item.WorkerNumber = item.newWorkerNumber;
item.WorkDay = item.newWorkDay;
item.AverageHourPerDay = item.newAverageHourPerDay;
if (item.oldScalar == item.Scalar) {
item.Scalar = item.WorkerNumber * item.WorkDay * item.AverageHourPerDay;
}
item.Description = item.newDescription;
modelWorkHour.push(item);
});
$http.post($scope.baseUrl+'/api/WorkHour/SaveWorkHours/', modelWorkHour).then(function (response) {
angular.forEach(modelWorkHour, function (entry, index) {
entry.KgCO2e = response.data.result[index].KgCO2e;
getAllDataAsync($routeParams.LCAID, $scope.selectedPeopleType).then(function (data) {
$scope.processWorkHoursData(data);
})
})
calculateDirectSum();
//calculateIndirectSum();
});;
};
$scope.cancelData = function () {
$scope.Editable = false;
doCancel($scope.modelDirectWorkHours);
doCancel($scope.modelIndirectWorkHours);
};
function doCancel(model) {
angular.forEach(model, function (item) {
item.newScalar = item.Scalar;
item.newDescription = item.Description;
//item.newYear.Year = item.Year;
});
}
$scope.editProcess = function (selected) {
$scope.Editable = true;
doEdit($scope.modelDirectWorkHours);
doEdit($scope.modelIndirectWorkHours);
};
function doEdit(model) {
angular.forEach(model, function (item) {
item.newWorkerNumber = item.WorkerNumber;
item.newWorkDay = item.WorkDay;
item.newDescription = item.Description;
item.newAverageHourPerDay = item.AverageHourPerDay;
});
}
$scope.onAllocationChange = function (Allocation) {
$scope.Allocation = Allocation
if ($scope.Allocation == 0) //重量分配
//$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, $scope.product.Weight, $scope.lcaDetail.FabProductionWeight);
$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs * $scope.product.Weight / $scope.lcaDetail.FabProductionWeight, 1, $scope.lcaDetail.ProductProductionPcs);
else if ($scope.Allocation == 1) //面積分配
//$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, $scope.product.AreaSize, $scope.lcaDetail.FabProductionArea);
$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs * $scope.product.AreaSize / $scope.lcaDetail.FabProductionArea, 1, $scope.lcaDetail.ProductProductionPcs);
else if ($scope.Allocation == 2) //產量分配
//$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, 1, $scope.lcaDetail.FabProductionPcs);
$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, 1, $scope.lcaDetail.FabProductionPcs);
else if ($scope.Allocation == 3) //經濟分配
//$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, $scope.lcaDetail.ProductProductionEconomic, $scope.lcaDetail.FabProductionEconomic);
$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs * $scope.lcaDetail.ProductProductionEconomic / $scope.lcaDetail.FabProductionEconomic, 1, $scope.lcaDetail.ProductProductionPcs);
else if ($scope.Allocation == 4) //工時分配
//$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs, $scope.lcaDetail.ProductProductionHour, $scope.lcaDetail.FabProductionHour);
$scope.Ratio = $scope.calculate($scope.lcaDetail.ProductProductionPcs * $scope.lcaDetail.ProductProductionHour / $scope.lcaDetail.FabProductionHour, 1, $scope.lcaDetail.ProductProductionPcs);
else if ($scope.Allocation == 99)
$scope.Ratio = 1;
$http.post($scope.baseUrl+'/api/LCA/SaveAllocation/' + $routeParams.LCAID + '/' + $routeParams.DetailType + '/' + $scope.Allocation)
.success(function (data) {
$scope.modifyCacheAllocation();
})
}
$scope.dataQualityShow = function (selected) {
$http.get($scope.baseUrl+'/api/DataQualityLevel/GetByTableLCAID/' + $routeParams.LCAID + '/LCACommonSurveyForm_WorkHours/'
).success(function (data) {
angular.copy(data, $scope.dataQualityOption.data);
//todo !!... load pre saved data
//$scope.dataQualityOption.Fi = 0.0123;//test only;
//todo !!... 還需要總碳排量才能算出 碳排量佔比
$scope.dataQualityOption.show = true;
}).error(function (data, status) {
alert(data.ExceptionMessage);
});
};
}]);