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

614 lines
28 KiB
JavaScript
Raw Permalink Blame History

/*
** Views/Partial/LCA/OtherCompound.cshtml is using this controller
*/
angular.module('CarbonFootprint')
.controller('LCAOtherCompoundCtrl', ['$scope', '$http', '$routeParams', 'ParameterCacheService', 'JoinSurveyItemAndParameter', '$q', 'MultiLanguageService', 'ExportCsvService',
function ($scope, $http, $routeParams, ParameterCacheService, JoinService, $q, MultiLanguageService, ExportCsvService) {
// Multi-language resource object
var resource;
// This property controlls modal form , will be passed to table-edit-modal directive
$scope.modalFormOption = {};
$scope.summary = [];
$scope.sumKgCO2e = 0;
// 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.createProcess = function () {
// Create an object & select it
var toBeCreated = {};
var formData = new FormData;
var hasFile = false;
var fileIndex = -1;
toBeCreated.ID = 0;
toBeCreated.LCAID = $routeParams.LCAID;
toBeCreated.activityDataType = 0;
toBeCreated.emitParaType = 0;
// For modal form
$scope.selectRow.toBeEdit = toBeCreated;
$scope.selectFile = function (file) {
fileIndex = fileIndex + 1;
formData.append('of' + "_lca" + $routeParams.LCAID + "_" + fileIndex, file);
hasFile = true;
};
$scope.modalFormOption.show = true;
$scope.dataQualityOption = {};
$scope.dataQualityOption.data = {};
$scope.isEdit = false;
$scope.save = function () {
// Calculate KgCO2e
JoinService.joinAsync([toBeCreated]).then(function () {
// Update KgCO2e property
setKgCO2e([toBeCreated]);
$http.post($scope.baseUrl+'/api/Upload', formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (urlList) {
if (hasFile)
toBeCreated.ReferenceFileUrl = $scope.baseUrl +urlList[fileIndex];
$http.post($scope.baseUrl+'/api/OtherCompound/Save/' + $routeParams.LCAID + '/' + toBeCreated.ID, toBeCreated)
.success(function (data) {
$scope.model.unshift(data);
calcTotalKgCO2e();
$scope.modalFormOption.show = false;
});
});
});
};
};
$scope.editProcess = function (selected) {
var toBeEdit = $scope.selectRow.toBeEdit = angular.copy(selected);
var formData = new FormData();
var hasFile = false;
var fileIndex = -1;
toBeEdit.Source = selected.ARnGWPid;//.ParameterID;
$scope.selectFile = function (file) {
fileIndex = fileIndex + 1;
formData.append('of' + "_lca" + $routeParams.LCAID + "_" + fileIndex, file);
hasFile = true;
};
$scope.modalFormOption.show = true;
$scope.dataQualityOption = {};
$scope.dataQualityOption.data = {};
$scope.isEdit = true;
$('#activityDataType').val(selected.activityDataType);
$('#emitParaType').val(selected.emitParaType);
//console.log($scope.selectRow.toBeEdit);
$scope.save = function () {
// Calculate KgCO2e
JoinService.joinAsync([toBeEdit]).then(function () {
// Update KgCO2e property
setKgCO2e([toBeEdit]);
$http.post($scope.baseUrl+'/api/Upload', formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (urlList) {
if (hasFile)
toBeEdit.ReferenceFileUrl = $scope.baseUrl +urlList[fileIndex];
$http.post($scope.baseUrl+'/api/OtherCompound/Save/' + $routeParams.LCAID + '/' + toBeEdit.ID, toBeEdit)
.success(function (data) {
angular.copy(data, selected);
calcTotalKgCO2e();
$scope.modalFormOption.show = false;
})
.error(function (data, status) {
console.log(status);
});
});
});
};
};
$scope.dataQualityShow = function (selected) {
$http.get($scope.baseUrl+'/api/DataQualityLevel/GetByTableId/ProductLCAFabSurveyForm_OtherCompounds/' + selected.ID
).success(function (data) {
angular.copy(data, $scope.dataQualityOption.data);
$scope.dataQualityOption.data.Name = selected.Name;
$scope.dataQualityOption.data.LCAID = selected.LCAID;
//todo !!... load pre saved data
//$scope.dataQualityOption.Fi = 0.0123;//test only;
//todo !!... <20>ٻݭn<DDAD>`<60>ұƶq<C6B6>~<7E><><EFBFBD><EFBFBD><EFBFBD>X <20>ұƶq<C6B6><71><EFBFBD><EFBFBD>
$scope.dataQualityOption.showSaveBtn = $scope.lcaDetail.Status == 1;
$scope.dataQualityOption.show = true;
}).error(function (data, status) {
alert(data.ExceptionMessage);
});
};
$scope.deleteProcess = function (selected) {
var isConfirm = confirm(resource.DeleteItemMsg);
if (isConfirm) {
$http.delete($scope.baseUrl+'/api/OtherCompound/Delete/' + selected.ID+'/'+ $routeParams.LCAID)//CFT-50
.success(function () {
var index = $scope.model.indexOf(selected);
$scope.model.splice(index, 1);
calcTotalKgCO2e();
// This operate is base on selectRow directive in TableEdit.js file
$scope.selectRow.unSelect();
});
}
};
/* modelBuilder for create & export */
/** Caution!: The 'ParameterID' property depends on '$scope.sources'.
This modelBuilder is binded with this controller.
Refactoring modelBuilder.create() with more arugments will be better **/
$scope.modelBuilder = {
create: function (data, LCAID) {
try {
var model = {
ProcessName: data[0],
ResponsibleUnit: data[1],
Name: data[2],
ingredientName: data[3],
warmGasType: getWarmGasTypeKey(data[4]),
activityDataType: getKeyByValue(data[5], $scope.activityOptions),
emitParaType: getKeyByValue(data[6], $scope.emitParaOptions),
CO2Factor: data[7],
CO2Value: data[8],
CH4Value: data[9],
N2OValue: data[10],
HFCsValue: data[11],
PFCsValue: data[12],
SF6Value: data[13],
NF3Value: data[14],
paraSource: data[15],
Scalar: data[16],
Description: data[17],
LCAID: LCAID
};
// check imported data length and model length (-1 for LCAID)
if (data.length !== getObjectSize(model) - 1) {
throw resource['EXCELFileFormatWrong'];
}
return model;
} catch (err) {
return { error: err };
}
},
export: function (list) {
var data = [];
// header
data.push([resource['FactoryAndProcessItems'],
resource['ResponsibleUnit'],
resource['DeviceName'],
resource['IngredientName'],
resource['WarmGasType'],
resource['ActivityDataType'],
resource['EmitParaType'],
resource['CO2Factor'],
resource['CO2Value'],
resource['CH4Value'],
resource['N2OValue'],
resource['HFCsValue'],
resource['PFCsValue'],
resource['SF6Value'],
resource['NF3Value'],
resource['ParameterSource'],
resource['UsageAmount'],
resource['StaticLabelGlobal_Remark']]);
// body
angular.forEach(list, function (entry) {
var csv = [];
//column 1
csv.push(entry.ProcessName);
//column 2
csv.push(entry.ResponsibleUnit);
//column 3
csv.push(entry.Name);
//column 4
csv.push(entry.ingredientName);
//column 5
csv.push(getWarmGasType(entry.warmGasType));
//column 6
csv.push($scope.activityOptions[entry.activityDataType]);
//column 7
csv.push($scope.emitParaOptions[entry.emitParaType]);
//column 8
csv.push(entry.CO2Factor);
//column 9
csv.push(entry.CO2Value);
//column 10
csv.push(entry.CH4Value);
//column 11
csv.push(entry.N2OValue);
//column 12
csv.push(entry.HFCsValue);
//column 13
csv.push(entry.PFCsValue);
//column 14
csv.push(entry.SF6Value);
//column 15
csv.push(entry.NF3Value);
//column 16
csv.push(entry.paraSource);
//column 17
csv.push(entry.Scalar);
//column 18
csv.push(entry.Description);
data.push(csv);
});
//console.log('export', $scope.sources, list);
ExportCsvService.startExport(data, "Export_OtherCompound.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.OtherCompounds);
})
return deferred.promise;
},
saveAsyncFn: batchCreateAndUpdateCache
};
$scope.quoteModal = {
show: false
};
$scope.onSourceChange = function (newValue) {
//console.log('onSourceChange', newValue, $scope.selectRow.toBeEdit.Source,'>'+ $("#emissionSource option:selected").text().trim()+'<' );
$scope.selectRow.toBeEdit.ParameterID = newValue;
var toBeEdit = $scope.selectRow.toBeEdit;
getParameterValue(toBeEdit.LCAID, toBeEdit.ParameterID).then(function (data) {
//console.log('getParameterValue', data);
var GWPFactor = Number(data.ARnGWP);// Number(data[toBeEdit.ParameterID]);
//if (GWPFactor == 0) {
// $scope.selectRow.toBeEdit.GWPFactor = 1;
//}
//else {
//$scope.selectRow.toBeEdit.GWPFactor = GWPFactor;
$scope.selectRow.toBeEdit.CO2Factor = GWPFactor;// 1;
$scope.selectRow.toBeEdit.paraSource = $scope.ParameterSource;
$scope.selectRow.toBeEdit.ingredientName = $("#emissionSource option:selected").text().trim();
var hasValue = false;
if (data.GHGType == 'CH4') {
$scope.selectRow.toBeEdit.CH4Value = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.CH4Value = 0;
if (data.GHGType == 'N2O') {
$scope.selectRow.toBeEdit.N2OValue = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.N2OValue = 0;
if (data.GHGType == 'HFCs') {
$scope.selectRow.toBeEdit.HFCsValue = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.HFCsValue = 0;
if (data.GHGType == 'PFCs') {
$scope.selectRow.toBeEdit.PFCsValue = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.PFCsValue = 0;
if (data.GHGType == 'SF6') {
$scope.selectRow.toBeEdit.SF6Value = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.SF6Value = 0;
if (data.GHGType == 'NF3') {
$scope.selectRow.toBeEdit.NF3Value = GWPFactor;
hasValue = true;
} else
$scope.selectRow.toBeEdit.NF3Value = 0;
if (!hasValue)
$scope.selectRow.toBeEdit.CO2Value = GWPFactor;
else
$scope.selectRow.toBeEdit.CO2Value = 0;
//}
});
};
// Sync 'ParameterID' based on 'Source', because ngModel of <select> is bind to 'Source'
//$scope.$watch('selectRow.toBeEdit.Source', function (newValue) {
// $scope.selectRow.toBeEdit.ParameterID = newValue;
// var toBeEdit = $scope.selectRow.toBeEdit;
// getParameterValue(toBeEdit.ParameterID).then(function (data) {
// var GWPFactor = Number(data[toBeEdit.ParameterID]);
// //console.log('GWPFactor',data[toBeEdit.ParameterID]);
// if (GWPFactor == 0) {
// $scope.selectRow.toBeEdit.GWPFactor = 1;
// }
// else {
// $scope.selectRow.toBeEdit.GWPFactor = GWPFactor;
// $scope.selectRow.toBeEdit.CO2Factor = 1;
// }
// });
// //getParameterCO2Value(toBeEdit.ParameterID).then(function (data) {
// // var CO2Factor = Number(data[toBeEdit.ParameterID]);
// // //console.log('CO2Factor',data[toBeEdit.ParameterID]);
// // if (CO2Factor == 0) {
// // $scope.selectRow.toBeEdit.CO2Factor = 1;
// // }
// // else {
// // $scope.selectRow.toBeEdit.CO2Factor = CO2Factor;
// // }
// //});
//}, true);
// Get data and prepare $scope.model
getAllDataAsync($routeParams.LCAID)
.then(function (response) {
//console.log('getAllDataAsync', response);
var otherCompounds = response.OtherCompounds,
sources = response.Options;
var sheetHeader = response.SheetHeader ? response.SheetHeader : {};
$scope.model = otherCompounds;
calcTotalKgCO2e();
$scope.sources = sources;
$scope.sourcesArray = [];
$scope.ParameterSource = response.ParameterSource;
angular.forEach(sources, function (value, key) {
$scope.sourcesArray.push({ key: key, value: value });
});
$scope.sourcesArray.sort(function (obj1, obj2) {
return obj1.value.localeCompare(obj2.value);
});
// $scope.sheetHeader is parent's object
$scope.sheetHeader.SheetFillerName = sheetHeader.SheetFillerName;
$scope.sheetHeader.Phone = sheetHeader.Phone;
$scope.sheetHeader.Department = sheetHeader.Department;
$scope.activityOptions = response.ActivityOptions;
$scope.emitParaOptions = response.EmitParaOptions;
}, 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();
// Calculate KgCO2e and sava all
JoinService.joinAsync(parsedList)
.then(function () {
// update KgCO2e properties
setKgCO2e(parsedList);
$http.post($scope.baseUrl+'/api/OtherCompound/SaveAll/', parsedList)
.success(function (data) {
// close modals
$scope.fileImportModal.show = false;
$scope.quoteModal.show = false;
// concat created data and $scope.model
$scope.model = data.result.concat($scope.model);
calcTotalKgCO2e();
deferred.resolve(data);
})
.error(function (e) {
console.log(e.Message);
});
});
return deferred.promise;
}
/**
* Update the KgCO2e property of the model objects
* @param {[Array]} : array of model objects
*/
function setKgCO2e(models) {
angular.forEach(models, function (entry) {
if (/*entry.GWPFactor &&*/ entry.CO2Factor && entry.Scalar) {
entry.KgCO2e = //entry.GWPFactor *
entry.CO2Factor * entry.Scalar;
}
});
}
/**
* Get all list data from server
* @param {[Int]} : LCAID
* @return {[promise]}
*/
function getAllDataAsync(LCAID) {
var deferred = $q.defer();
$http.get($scope.baseUrl+'/api/OtherCompound/GetByLcaId/' + LCAID)
.success(function (data) {
//console.log(data);
deferred.resolve(data);
})
.error(function () {
deferred.resolve(null);
});
return deferred.promise;
}
function getParameterValue(LCAID, ARnId) {
var /*result = [],
toBeQuery = [],*/
deferred = $q.defer();
//toBeQuery.push(ID);
//if (toBeQuery.length != 0) {
$http.get($scope.baseUrl+'/api/Parameter/GetGWPs/' + LCAID + '/' + ARnId)// toBeQuery)
.success(function (data) {
//console.log('GetGWPs', data);
result = data;
//angular.forEach(data, function (value, key) {
// result[key] = value;
//});
deferred.resolve(result);
});
//} else {
// deferred.resolve(result);
//}
return deferred.promise;
}
function getParameterCO2Value(ID) {
var result = [],
toBeQuery = [],
deferred = $q.defer();
toBeQuery.push(ID);
if (toBeQuery.length != 0) {
$http.post($scope.baseUrl+'/api/Parameter/getParameterCO2Values', toBeQuery)
.success(function (data) {
angular.forEach(data, function (value, key) {
result[key] = value;
});
deferred.resolve(result);
});
} else {
deferred.resolve(result);
}
return deferred.promise;
}
function getWarmGasType(key) {
if (key == 1)
return resource['fixedSource'];
else if (key == 2)
return resource['movingSource'];
else if (key == 3)
return resource['escapeSource'];
else if (key == 4)
return resource['manufactureSource'];
else if (key == 5)
return resource['landUsageSource'];
else if (key == 6)
return resource['externalEnergySource'];
else
return '';
}
function getWarmGasTypeKey(value) {
if (value == resource['fixedSource'])
return 1;
else if (value == resource['movingSource'])
return 2;
else if (value == resource['escapeSource'])
return 3;
else if (value == resource['manufactureSource'])
return 4;
else if (value == resource['landUsageSource'])
return 5;
else if (value == resource['externalEnergySource'])
return 6;
else
return 0;
}
function getKeyByValue(value, map) {
var keys = Object.keys(map);
for (var i = 0; i <= keys.length; i++) {
if (value == map[keys[i]]) {
return i
}
}
return 0;
}
function calcTotalKgCO2e() {
$scope.summary = Enumerable.From($scope.model).GroupBy("$.ingredientName", "$.KgCO2e", function (key, group) {
return { ingredientName: key, totalKgCO2e: Enumerable.From(group).Sum(), AllocationKgCO2e: Enumerable.From(group).Sum() * $scope.Ratio };
}).ToArray();
var sumKgCO2e = 0;
angular.forEach($scope.summary, function (item) {
sumKgCO2e += item.totalKgCO2e;
});
$scope.sumKgCO2e = sumKgCO2e;
}
$scope.onAllocationChange = function (Allocation) {
$scope.Allocation = Allocation
if ($scope.Allocation == 0) //<2F><><EFBFBD>q<EFBFBD><71><EFBFBD>t
//$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) //<2F><><EFBFBD>n<EFBFBD><6E><EFBFBD>t
//$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) //<2F><><EFBFBD>q<EFBFBD><71><EFBFBD>t
//$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) //<2F>g<EFBFBD>٤<EFBFBD><D9A4>t
//$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) //<2F>u<EFBFBD>ɤ<EFBFBD><C9A4>t
//$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) {
calcTotalKgCO2e();
$scope.modifyCacheAllocation();
})
}
}]);