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

367 lines
17 KiB
JavaScript
Raw Permalink Blame History

/*
** Views/Partial/LCA/OtherCompound.cshtml is using this controller
*/
angular.module('CarbonFootprint')
.controller('LCAFireEquipmentCtrl', ['$scope', '$http', '$routeParams', 'JoinSurveyItemAndParameter', '$q', 'MultiLanguageService', 'ExportCsvService',
function ($scope, $http, $routeParams, 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.model = [];
$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;
}
// Sync 'ParameterID' based on 'Source', because ngModel of <select> is bind to 'Source'
$scope.$watch('selectRow.toBeEdit.Source', function (newValue) {
var toBeEdit = $scope.selectRow.toBeEdit;
angular.forEach($scope.sources, function(value, key) {
if (value === newValue) {
toBeEdit.ParameterID = key;
}
});
}, true);
$scope.createProcess = function () {
//new an object & select it
var toBeCreated = {};
toBeCreated.ID = 0;
toBeCreated.LCAID = $routeParams.LCAID;
toBeCreated.activityDataType = 0;
toBeCreated.emitParaType = 0;
// For modal form
$scope.selectRow.toBeEdit = toBeCreated;
$scope.modalFormOption.show = true;
$scope.dataQualityOption = {};
$scope.dataQualityOption.data = {};
$scope.isEdit = false;
$scope.save = function () {
// Join parameter value and calculate KgCO2e
JoinService.joinAsync([toBeCreated]).then(function () {
//console.log('save create', [toBeCreated]);
// Update KgCO2e property
//setKgCO2e([toBeCreated]);
$http.post($scope.baseUrl+'/api/FireEquipment/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);
toBeEdit.Source = $scope.sources[selected.ParameterID];
$scope.modalFormOption.show = true;
$scope.dataQualityOption = {};
$scope.dataQualityOption.data = {};
$scope.isEdit = true;
$('#activityDataType').val(selected.activityDataType);
$('#emitParaType').val(selected.emitParaType);
$scope.save = function () {
JoinService.joinAsync([toBeEdit]).then(function () {
console.log('save edit', [toBeEdit]);
// Update KgCO2e property
//setKgCO2e([toBeEdit]);
console.log('save edit before post', toBeEdit);
$http.post($scope.baseUrl+'/api/FireEquipment/Save/' + $routeParams.LCAID + '/' + toBeEdit.ID, toBeEdit)
.success(function (data) {
angular.copy(data, selected);
calcTotalKgCO2e();
$scope.modalFormOption.show = false;
});
});
};
};
$scope.dataQualityShow = function (selected) {
$http.get($scope.baseUrl + '/api/DataQualityLevel/GetByTableId/LCACommonSurveyForm_FireEquipments/' + 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/FireEquipment/Delete/' + selected.ID)
.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],
ParameterID: getKeyByValue($scope.sources, data[3]),
Quantity: data[4],
Scalar: parseFloat(data[5]) ? data[5] : 0,
Description: data[6],
LCAID: LCAID
};
// check imported data length and model length (-1 for LCAID)
if (data.length !== getObjectSize(model) - 1) {
throw resource['EXCELFileFormatWrong'];
}
// if find incorrect ParameterID
if (model.ParameterID === undefined) {
throw resource['EmissionSources'] + ' Error';
}
return model;
} catch (err) {
return { error: err };
}
},
export: function (list) {
var data = [];
// header
data.push([resource['FactoryAndProcessItems'],
resource['ResponsibleUnit'],
resource['DeviceName'],
resource['EmissionSources'],
resource['Quantity'],
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($scope.sources[entry.ParameterID]);
//column 5
csv.push(entry.Quantity);
//column 6
csv.push(entry.Scalar);
//column 7
csv.push(entry.Description);
data.push(csv);
});
ExportCsvService.startExport(data, "Export_FireEquipment.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.FireEquipments);
})
return deferred.promise;
},
saveAsyncFn: batchCreateAndUpdateCache
};
$scope.quoteModal = {
show: false
};
// Get data and prepare $scope.model
getAllDataAsync($routeParams.LCAID)
.then(function (response) {
var fireEquipments = response.FireEquipments,
sources = response.Options;
var sheetHeader = response.SheetHeader ? response.SheetHeader : {};
//console.log(response);
$scope.model = fireEquipments;
$scope.sources = sources;
//console.log('$scope.model', $scope.model);
//console.log(response.Options);
//console.log(sources);
calcTotalKgCO2e();
// $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/FireEquipment/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.parameterResult && entry.Scalar && entry.Quantity) {
entry.KgCO2e = entry.parameterResult * parseFloat(entry.Scalar)* parseFloat(entry.Quantity);
} else {
entry.KgCO2e = 0;
}
});
}
/**
* Get all list data from server
* @param {[Int]} : LCAID
* @return {[promise]}
*/
function getAllDataAsync(LCAID) {
var deferred = $q.defer();
$http.get($scope.baseUrl+'/api/FireEquipment/GetByLcaId/' + LCAID)
.success(function (data) {
deferred.resolve(data);
})
.error(function () {
deferred.resolve(null);
});
return deferred.promise;
}
function calcTotalKgCO2e() {
$scope.summary = Enumerable.From($scope.model).GroupBy("$.ParameterID", "$.KgCO2e", function (key, group) {
return { ParameterID: 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();
})
}
}]);