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

492 lines
20 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
** Views/Partial/LCA/SteamUsage.cshtml is using this controller
*/
angular.module('CarbonFootprint')
.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.form = {
factor: "0.0000",
factorSource: ""
};
//$scope.factor = "0.0000";
$scope.yearSelected = {};
// 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.uploadFile = function (rowIndex) {
UploadFile.uploadFile($scope, $scope.model[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
};
// check imported data length and model length (-1 for LCAID)
// +1 for month column
if (data.length !== getObjectSize(model) - 1 + 1) {
throw resource['EXCELFileFormatWrong'];
}
return model;
} catch (err) {
return { error: err };
}
},
export: function (list) {
var data = [];
// header
data.push([resource['StaticLabelGlobal_Month'],
resource['UsageAmount'],
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_SteamUsage.csv");
}
}
/* 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.SteamUsages.sort((a, b) => a.Index - b.Index));
})
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 steamUsages = response[1].data.SteamUsages;
var sheetHeader = response[1].data.SheetHeader ? response[1].data.SheetHeader : {};
//console.log('response[1].data', response[1].data);
if (response[1].data.SteamUsages.length > 0) {
$scope.form.factor = response[1].data.SteamUsages[0].Factor;
$scope.form.factorSource = response[1].data.SteamUsages[0].FactorSource;
}
else {
$scope.form.factor = response[1].data.factor;
$scope.form.factorSource = response[1].data.factorSource;
}
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 (steamUsages.length > 0 && (steamUsages.length - i - 1) >= 0) {
var row = steamUsages[steamUsages.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];
$scope.areaSelected = area;
//console.log('changeYear', $scope.areaSelected);
};
$scope.onYearChange = function (theYear) {
$scope.yearSelected = theYear;
//console.log('onYearChange', theYear);
// 這裡要call api 取得排放係數
$http.get($scope.baseUrl+'/api/Parameter/GetValue/' + theYear.ParameterID)
.success(function (data, status, headers, config) {
$scope.form.factor = parseFloat(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',theActivity);
$scope.activityDataType = theActivity;
};
$scope.onEmitparaChange = function (theEmitpara) {
//console.log('onEmitparaChange',theEmitpara);
$scope.emitParaType = theEmitpara;
};
$scope.sources = sources;
calculateSum();
//CFT-104, set area to taiwan by default.
var lang = $cookies._culture;
if (lang == "zh-tw") {
$scope.areaSelected = "台灣";
} else if (lang == "zh-cn") {
$scope.areaSelected = "台湾";
} else if (lang == "en-us") {
if (area && angular.isArray(area)) {
for (var i = 0; i < area.length; i++) {
if (area[i].toLowerCase() == "taiwan") {
$scope.areaSelected = area[i];
break;
}
}
}
}
$scope.changeYear($scope.areaSelected);
// initial year
if (steamUsages.length > 0) {
//console.log('steamUsages[0]', steamUsages[0]);
$scope.areaSelected = steamUsages[0].Area;
$scope.changeYear($scope.areaSelected);
$scope.yearSelected.Year = steamUsages[0].Year;
$scope.yearSelected.ParameterID = steamUsages[0].ParameterID;
//if (steamUsages[0].Factor != null) {
// $scope.factor = steamUsages[0].Factor;
//}
}
// $scope.sheetHeader is parent's object
$scope.sheetHeader.SheetFillerName = sheetHeader.SheetFillerName;
$scope.sheetHeader.Phone = sheetHeader.Phone;
$scope.sheetHeader.Department = sheetHeader.Department;
//console.log('lcaDetail',lcaDetail);
$scope.activityDataType = 0;
$scope.emitParaType = 0;
$scope.activityOptions = response[1].data.ActivityOptions;
$scope.emitParaOptions = response[1].data.EmitParaOptions;
// !!... 這裡無論如何都無法更新api回覆的選項反應在dropdown上
//$scope.activityDataType = lcaDetail.activityDataTypeSteamUsage;
//$scope.emitParaType = lcaDetail.emitParaTypeSteamUsage;
//$('#activityDataType').val(lcaDetail.activityDataTypeSteamUsage);
//$('#emitParaType').val(lcaDetail.emitParaTypeSteamUsage);
$timeout(function () {
//console.log('$timeout', lcaDetail);
$scope.activityDataType = lcaDetail.activityDataTypePowerUsage;
$scope.emitParaType = lcaDetail.emitParaTypePowerUsage;
});
}, 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 (response) {
resource = response;
}, 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();
// 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
// need to clear LCA cache since the save api may change activityDataTypePowerUsage and emitParaTypePowerUsage
LCADetailCacheService.clearLCADetailFromCache($routeParams.LCAID);
$http.post($scope.baseUrl+'/api/SteamUsage/SaveSteamUsages/' + $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
} else {
$scope.model[i].Scalar = 0;
}
$scope.model[i].Year = null;
$scope.model[i].KgCO2e = 0;
$scope.model[i].Description = data.result[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/SteamUsage/GetSteamUsages/' + 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.newYear.Year;
item.Description = item.newDescription;
item.ParameterID = $scope.yearSelected.ParameterID;//item.newYear.ParameterID;
item.Area = $scope.areaSelected;
item.Factor = $scope.form.factor;
item.FactorSource = $scope.form.factorSource;
});
// need to clear LCA cache since the save api may change activityDataTypePowerUsage and emitParaTypePowerUsage
LCADetailCacheService.clearLCADetailFromCache($routeParams.LCAID);
//console.log('2', $scope.model);
$http.post($scope.baseUrl+'/api/SteamUsage/SaveSteamUsages/' + $routeParams.LCAID + '/'
+ getActivityDataType() + '/' + getEmitParaType()
, $scope.model).then(function (response) {
for (var i = 0; i < $scope.model.length; i++) {
$scope.model[i].KgCO2e = response.data.result[i].KgCO2e;
}
//angular.forEach($scope.model, function (entry, index) {
// entry.KgCO2e = data.result[index].KgCO2e;
//})
calculateSum();
//})
//.error(function (e) {
// console.log(e.Message);
});
};
$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 + '/LCACommonSurveyForm_SteamUsages/'
).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);
});
};
}]);