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

509 lines
21 KiB
JavaScript

/*
** Views/Partial/LCA/WaterUsage.cshtml is using this controller
*/
angular.module('CarbonFootprint')
.controller('LCAWaterUsageCtrl', ['$q', '$scope', '$http', '$routeParams', '$cookies', '$timeout', 'ParameterCacheService', 'LCADetailCacheService', 'DATE_CONSTANTS', 'UploadFile', 'MultiLanguageService', 'ExportCsvService',
function ($q, $scope, $http, $routeParams, $cookies, $timeout, ParameterCacheService, LCADetailCacheService, DATE_CONSTANTS, UploadFile, MultiLanguageService, ExportCsvService) {
// .controller('LCASteamUsageCtrl', ['$q', '$scope', '$http', '$routeParams', '$cookies', '$timeout', 'ParameterCacheService', 'LCADetailCacheService', 'DATE_CONSTANTS', 'UploadFile', 'MultiLanguageService', 'ExportCsvService',
// function ($q, $scope, $http, $routeParams, $cookies, $timeout, 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.yearSelected = {};
$scope.factor = "0.0000";
// 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;
}
// 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.uploadFileNormal = function (rowIndex) {
UploadFile.uploadFile($scope, $scope.modelPowerNormal[rowIndex]);
};
/* modelBuilder for create & export */
$scope.modelBuilder = {
create: function (data, LCAID) {
try {
var model = {
// importing only depends on the order of data, not month
Scalar: parseFloat(data[1]) ? data[1].replaceAll(',', '') : 0,
Description:data[2],
ReferenceFileLink: data[3],
LCAID: LCAID,
//Year: $scope.yearSelected.Year,
//Area: $scope.areaSelected,
//ParameterID: $scope.yearSelected.ParameterID
};
if (data.length !== getObjectSize(model) - 3)
throw Resource['EXCELFileFormatWrong'];
return model;
}
catch (err) {
return { error: err };
}
},
export: function (list, exportType = 'txt') {
if (exportType == 'csv') {
var data = [];
// header
data.push([
Resource['StaticLabelGlobal_Month'],
Resource['WaterUsage'],
Resource['DescriptionAndExplanation'],
Resource['StaticLabelEvidenceOfElectronicFile'] + Resource['StaticLabelEvidenceOfElectronicFileDescription']
]);
// body
angular.forEach(list, function (entry) {
var csv = [];
//column 1
csv.push(entry.Month);
//column 2
csv.push(entry.Scalar);
//column 3
csv.push(entry.Description);
//column 4
csv.push(entry.ReferenceFileLink);
data.push(csv);
})
ExportCsvService.startExport(data, "Export_WaterUsage.csv");
}
else {
var csv = '\uFEFF';
var delimeter = '\t';
// header
csv += Resource['StaticLabelGlobal_Month'] + delimeter
+ Resource['WaterUsage'] + delimeter
+ Resource['DescriptionAndExplanation'] + delimeter
+ Resource['StaticLabelEvidenceOfElectronicFile'] + Resource['StaticLabelEvidenceOfElectronicFileDescription'];
// body
angular.forEach(list, function (entry) {
csv += '\r\n';
//column 1
csv += entry.Month + delimeter
//column 2
csv += entry.Scalar + delimeter;
//column 3
csv += entry.Description + delimeter
//column 4
csv += entry.ReferenceFileLink;
})
var filename = "Export_WaterUsage.txt";
require([baseUrl+'/Scripts/FileSaver.js'],
function requrieSuccess(SaveAs) {
var textFileAsBlob = new Blob([csv], { type: 'text;charset=utf-8,' });
saveAs(textFileAsBlob, filename)
},
function requireError(error) {
}
);
}
}
}
/* file import options & modal control */
$scope.fileImportOptions = {
modelBuilder: $scope.modelBuilder,
saveAsync: batchCreateAndUpdateCache
};
$scope.fileImportModal = {
show: false
}
/* quote options & modal control */
$scope.quoteOptions = {
queryDataAsyncFn: function (LCAID) {
var deferred = $q.defer();
getAllDataAsync(LCAID).then(function (data) {
deferred.resolve(data[1].data.WaterUsages.sort((a, b) => a.Index - b.Index)); // b - a for reverse sort);
})
return deferred.promise;
},
saveAsyncFn: batchCreateAndUpdateCache
}
$scope.quoteModal = {
show: false
}
// Get data and prepare $scope.model
getAllDataAsync($routeParams.LCAID)
.then(function (response) {
var lcaDetail = response[0];
var waterUsages = response[1].data.WaterUsages;
var sheetHeader = response[1].data.SheetHeader ? response[1].data.SheetHeader : {};
$scope.factor = response[1].data.factor;
var sources = response[1].data.options;
// prepare area and correspondent year
var area = [];
var yearSource = {};
var areaYear = [];
for (var key in sources) {
var items = sources[key].split(',');
if (area.indexOf(items[0]) === -1)
area.push(items[0]);
if (typeof yearSource[items[0]] === 'undefined')
yearSource[items[0]] = [];
yearSource[items[0]].push({ Year: items[2], ParameterID: parseInt(key) });
}
for (var key in yearSource) {
yearSource[key].sort(function (y1, y2) {
return y1.Year - y2.Year;
});
}
var startDate = new Date(lcaDetail.StartDate);
var endDate = new Date(lcaDetail.EndDate);
// 將起訖日期改為同年第一與最後一天
startDate.setMonth(0, 1);
endDate.setMonth(11, 31);
// prepare row data
var steamModel = [];
var currentDate = startDate;
var i = 0;
while (currentDate < endDate) {
if (waterUsages.length > 0 && (waterUsages.length - i - 1) >= 0) {
var row = waterUsages[waterUsages.length - i - 1];
row.Month = DATE_CONSTANTS.months[currentDate.getMonth()];
row.showYear = currentDate.getFullYear();
row.newYear = { Year: row.Year, ParameterID: row.ParameterID };
steamModel[i++] = row;
}
else {
steamModel[i++] = {
ID: 0,
Index: i,
Year: 0,
newYear: {},
Scalar: 0,
Month: DATE_CONSTANTS.months[currentDate.getMonth()],
showYear: currentDate.getFullYear(),
ReferenceFileLink: '',
LCAID: $routeParams.LCAID,
KgCO2e: 0,
Description: ""
};
}
currentDate.setMonth(currentDate.getMonth() + 1);
}
$scope.model = steamModel;
$scope.area = area;
$scope.areaYear = areaYear;
$scope.changeYear = function (area) {
$scope.areaYear = yearSource[area];
//console.log(area); // 這偶而會null, 先保留
$scope.areaSelected = area;
};
$scope.onYearChange = function (theYear) {
$scope.yearSelected = theYear;
// 這裡要call api 取得排放係數
$http.get($scope.baseUrl + '/api/Parameter/GetValue/' + theYear.ParameterID)
.success(function (data, status, headers, config) {
//console.log('success', data, status, headers, config);
//$('#emitFactor').val(data);
$scope.factor = data;
})
.error(function (data, status, headers, config) {
//console.log('error', data, status);
console.log('error', data, status, headers, config);
});
};
$scope.onActivityChange = function (theActivity) {
//console.log('onActivityChange');
//console.log(theActivity);
$scope.activityDataType = theActivity;
};
$scope.onEmitparaChange = function (theEmitpara) {
//console.log('onEmitparaChange');
//console.log(theEmitpara);
$scope.emitParaType = theEmitpara;
};
$scope.sources = sources;
calculateSum();
if (typeof ($scope.areaSelected) !== 'undefined')
$scope.changeYear($scope.areaSelected);
// initial year
if (waterUsages.length > 0) {
$scope.areaSelected = waterUsages[0].Area;
$scope.changeYear($scope.areaSelected);
$scope.yearSelected.Year = waterUsages[0].Year;
$scope.yearSelected.ParameterID = waterUsages[0].ParameterID;
}
// $scope.sheetHeader is parent's object
$scope.sheetHeader.SheetFillerName = sheetHeader.SheetFillerName;
$scope.sheetHeader.Phone = sheetHeader.Phone;
$scope.sheetHeader.Department = sheetHeader.Department;
$scope.activityDataType = 0;
$scope.emitParaType = 0;
$scope.activityOptions = response[1].data.ActivityOptions;
$scope.emitParaOptions = response[1].data.EmitParaOptions;
$timeout(function () {
//console.log('$timeout', lcaDetail);
$scope.activityDataType = lcaDetail.activityDataTypeWaterUsage;
$scope.emitParaType = lcaDetail.emitParaTypeWaterUsage;
});
}, 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);
});
// 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.uploadFile = function (rowIndex) {
UploadFile.uploadFile($scope, $scope.model[rowIndex]);
};
/**
* Private function: save all async
* @param {[Array]} : array of parsed objects
* @return {[promise]}
*/
function batchCreateAndUpdateCache(parsedList) {
var deferred = $q.defer();
// remove redundant content
if (parsedList.length > $scope.model.length) {
parsedList.splice($scope.model.length, parsedList.length - $scope.model.length);
}
//set index by order
var index = 1
angular.forEach(parsedList, function (item) {
item.Index = index;
index++;
})
// sava all
//$http.post($scope.baseUrl+'/api/WaterUsage/SaveWaterUsages/', parsedList)
$http.post($scope.baseUrl + '/api/WaterUsage/SaveWaterUsages/' + $routeParams.LCAID + '/'
+ getActivityDataType() + '/' + getEmitParaType(), parsedList)
.success(function (data) {
// close modals
$scope.fileImportModal.show = false;
$scope.quoteModal.show = false;
// update $scope.model
for (var i = 0; i < $scope.model.length; i++) {
if (data.result[i])
{
$scope.model[i].Scalar = data.result[i].Scalar;
$scope.model[i].Description = data.result[i].Description
$scope.model[i].Year = data.result[i].Year
$scope.model[i].KgCO2e = data.result[i].KgCO2e
}
else {
$scope.model[i].Scalar = 0;
$scope.model[i].Year = null;
$scope.model[i].KgCO2e = 0;
$scope.model[i].Description = '';
}
}
calculateSum();
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) {
var deferred = $q.defer();
$q.all([LCADetailCacheService.getLCADetailAsync(LCAID),
$http.get($scope.baseUrl+'/api/WaterUsage/GetWaterUsages/' + LCAID)])
.then(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function calculateSum() {
var sumScalar = 0;
var sumKgCO2e = 0;
angular.forEach($scope.model, function (item) {
sumScalar += item.Scalar;
sumKgCO2e += item.KgCO2e;
});
$scope.sumScalar = sumScalar;
$scope.sumKgCO2e = sumKgCO2e;
}
function getActivityDataType() {
var activityDataType = $('#activityDataType').val();// $scope.activityDataType;
if (typeof (activityDataType) === 'undefined')
activityDataType = 0;
return activityDataType;
}
function getEmitParaType() {
var emitParaType = $('#emitParaType').val();// $scope.emitParaType;
if (typeof (emitParaType) === 'undefined')
emitParaType = 0;
return emitParaType;
}
$scope.saveData = function () {
$scope.Editable = false;
angular.forEach($scope.model, function (item) {
item.Scalar = item.newScalar;
item.Year = $scope.yearSelected.Year;
item.Description = item.newDescription;
item.ParameterID = $scope.yearSelected.ParameterID;
item.Area = $scope.areaSelected;
});
LCADetailCacheService.clearLCADetailFromCache($routeParams.LCAID);
//$http.post($scope.baseUrl+'/api/WaterUsage/SaveWaterUsages/', $scope.model).then(function (response) {
$http.post($scope.baseUrl + '/api/WaterUsage/SaveWaterUsages/' + $routeParams.LCAID + '/'
+ getActivityDataType() + '/' + getEmitParaType()
, $scope.model).then(function (response) {
angular.forEach($scope.model, function (entry, index) {
entry.KgCO2e = response.data.result[index].KgCO2e;
})
calculateSum();
});
};
$scope.cancelData = function () {
$scope.Editable = false;
angular.forEach($scope.model, function (item) {
item.newScalar = item.Scalar;
item.newDescription = item.Description;
item.newYear.Year = item.Year;
item.ReferenceFileLink = item.newReferenceFileLink;
});
};
$scope.editProcess = function (selected) {
$scope.Editable = true;
angular.forEach($scope.model, function (item) {
item.newScalar = item.Scalar;
item.newDescription = item.Description;
item.newYear.ParameterID = item.ParameterID;
item.newReferenceFileLink = item.ReferenceFileLink;
});
};
$scope.deleteFile = function (row) {
if (confirm(Resource['DeleteItemMsg'])) {
row.ReferenceFileLink = '';
}
};
$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 () {
$http.get($scope.baseUrl+'/api/DataQualityLevel/GetByTableLCAID/' + $routeParams.LCAID + '/ProductLCAFabSurveyForm_WaterUsages/'
).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);
});
};
}]);