Merge "Fix issues reported by sonar"
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / DecisionPolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http', function ($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) {
21     $("#dialog").hide();
22     
23     $scope.policyNavigator;
24     $scope.savebutton = true;
25     $scope.refreshCheck = false;
26     $scope.disableOnCreate = false;
27     
28     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
29         $scope.disableOnCreate = true;
30         $scope.temp.policy = {
31                         policyType : "Decision"
32         }
33     };
34     
35     $scope.refresh = function(){
36         if($scope.refreshCheck){
37                 $scope.policyNavigator.refresh();
38         }
39         $scope.modal('createNewPolicy', true);
40         $scope.temp.policy = "";
41     };
42     
43     $scope.modal = function(id, hide) {
44         return $('#' + id).modal(hide ? 'hide' : 'show');
45     };
46
47         if($scope.temp.policy.ruleProvider==undefined){
48                 $scope.temp.policy.ruleProvider="Custom";
49         }
50         
51         if($scope.temp.policy.blackListEntryType==undefined){
52                 $scope.temp.policy.blackListEntryType="Use Manual Entry";
53         }
54         
55         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
56                 var j = data;
57                 $scope.data = JSON.parse(j.data);
58                 console.log($scope.data);
59                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
60                 console.log($scope.onapNameDictionaryDatas);
61         }, function (error) {
62                 console.log("failed");
63         });
64
65         PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function (data) {
66                 var j = data;
67                 $scope.data = JSON.parse(j.data);
68                 console.log($scope.data);
69                 $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas);
70                 console.log($scope.settingsDictionaryDatas);
71         }, function (error) {
72                 console.log("failed");
73         });
74
75         PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function (data) {
76                 var j = data;
77                 $scope.data = JSON.parse(j.data);
78                 console.log($scope.data);
79                 $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas);
80                 console.log($scope.functionDefinitionDatas);
81         }, function (error) {
82                 console.log("failed");
83         });
84
85         PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function (data) {
86                 var j = data;
87                 $scope.data = JSON.parse(j.data);
88                 console.log($scope.data);
89                 $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas);
90                 console.log($scope.attributeDictionaryDatas);
91         }, function (error) {
92                 console.log("failed");
93         });
94
95         PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function (data) {
96                 var j = data;
97                 $scope.data = JSON.parse(j.data);
98                 console.log($scope.data);
99         $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas);
100                 console.log($scope.rainyDayDictionaryDatas);
101         }, function (error) {
102                 console.log("failed");
103         });
104         
105     PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function (data) {
106         var j = data;
107         $scope.data = JSON.parse(j.data);
108         console.log($scope.data);
109         $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas);
110         console.log($scope.rainyDayDictionaryDatasEntity);
111     }, function (error) {
112         console.log("failed");
113     });
114
115     function extend(obj, src) {
116         for (var key in src) {
117             if (src.hasOwnProperty(key)) obj[key] = src[key];
118         }
119         return obj;
120     }
121     
122     $scope.saveDecisionPolicy = function(policy){
123         if(policy.itemContent != undefined){
124                 $scope.refreshCheck = true; 
125                 $scope.policyNavigator = policy.itemContent;
126                 policy.itemContent = "";
127         }
128         $scope.savebutton = false;
129         console.log(policy);
130         var uuu = "policycreation/save_policy";
131                 var postData={policyData: policy};
132                 $.ajax({
133                         type : 'POST',
134                         url : uuu,
135                         dataType: 'json',
136                         contentType: 'application/json',
137                         data: JSON.stringify(postData),
138                         success : function(data){
139                                 $scope.$apply(function(){
140                                         $scope.data=data.policyData;
141                                         if($scope.data == 'success'){
142                                                 $scope.temp.policy.readOnly = 'true';
143                                                 Notification.success("Policy Saved Successfully.");     
144                                         }else if ($scope.data == 'PolicyExists'){
145                                                 $scope.savebutton = true;
146                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
147                                         }       
148                                 });
149                                 console.log($scope.data);
150                                 
151                         },
152                         error : function(data){
153                                 Notification.error("Error Occured while saving Policy.");
154                         }
155                 });
156     };
157     
158     $scope.validatePolicy = function(policy){
159         console.log(policy);
160         document.getElementById("validate").innerHTML = "";
161          var uuu = "policyController/validate_policy.htm";
162                 var postData={policyData: policy};
163                 $.ajax({
164                         type : 'POST',
165                         url : uuu,
166                         dataType: 'json',
167                         contentType: 'application/json',
168                         data: JSON.stringify(postData),
169                         success : function(data){
170                                 $scope.$apply(function(){
171                                         $scope.validateData = data.data.replace(/\"/g, "");
172                                                 $scope.data=data.data;
173                                                 if($scope.data == '"success"'){
174                                                         Notification.success("Validation Success.");
175                                                         $scope.savebutton = false;
176                                                 }else{
177                                                         Notification.error("Validation Failed.");
178                                                         document.getElementById("validate").innerHTML = $scope.validateData;
179                                                         document.getElementById("validate").style.color = "white";
180                                                         document.getElementById("validate").style.backgroundColor = "red";
181                                                         $scope.savebutton = true;
182                                                 }
183                                                 
184                                 });
185                                 console.log($scope.data);
186                         },
187                         error : function(data){
188                                 Notification.error("Validation Failed.");
189                                 $scope.savebutton = true; 
190                         }
191                 });
192     };
193    
194     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
195         $scope.temp.policy.attributes = [];
196         $scope.temp.policy.settings = [];
197         $scope.temp.policy.ruleAlgorithmschoices = [];
198         if(!$scope.temp.policy.yamlparams){
199                 $scope.temp.policy.yamlparams = {};
200         }
201         if(!$scope.temp.policy.yamlparams.targets){
202                 $scope.temp.policy.yamlparams.targets = [];
203         }
204         if(!$scope.temp.policy.yamlparams.blackList){
205                 $scope.temp.policy.yamlparams.blackList = [];
206         }
207         if(!$scope.temp.policy.rainyday){
208                 $scope.temp.policy.rainyday = {};
209         }
210         if(!$scope.temp.policy.rainyday.treatmentTableChoices){
211                 $scope.temp.policy.rainyday.treatmentTableChoices = [];
212         }
213     
214     }else if($scope.temp.policy.ruleProvider=="Custom"){
215            if($scope.temp.policy.attributes.length == 0){
216                    $scope.temp.policy.attributes = [];    
217            }
218            if($scope.temp.policy.settings.length == 0){
219                    $scope.temp.policy.settings = [];
220            }
221            if($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0){
222                    $scope.temp.policy.ruleAlgorithmschoices = [];
223            }
224     }else if($scope.temp.policy.ruleProvider=="GUARD_BL_YAML"){
225         if($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length==0){
226                 $scope.temp.policy.yamlparams.blackList = [];
227         }
228         if($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length==0){
229                 $scope.temp.policy.blackListEntries = [];
230         }
231         $scope.blackListEntries = [];
232         $scope.temp.policy.appendBlackListEntries = [];
233         $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
234     }else if($scope.temp.policy.ruleProvider=="GUARD_YAML"){
235         if($scope.temp.policy.yamlparams.targets.length==0){
236                    $scope.temp.policy.yamlparams.targets = [];
237                 }
238     }else if($scope.temp.policy.ruleProvider=="Rainy_Day"){
239         if($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0){
240                 $scope.temp.policy.rainyday.treatmentTableChoices = [];
241         }
242     }
243     $scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
244     $scope.addNewChoice = function() {
245       var newItemNo = $scope.temp.policy.attributes.length+1;
246       $scope.temp.policy.attributes.push({'id':'choice'+newItemNo});
247     };    
248     $scope.removeChoice = function() {
249       var lastItem = $scope.temp.policy.attributes.length-1;
250       $scope.temp.policy.attributes.splice(lastItem);
251     };
252     
253     $scope.settingsDatas = [{"settings" : $scope.temp.policy.settings}];
254     $scope.addNewSettingsChoice = function() {
255       var newItemNo = $scope.temp.policy.settings.length+1;
256       $scope.temp.policy.settings.push({'id':'choice'+newItemNo});
257     };    
258     $scope.removeSettingsChoice = function() {
259       var lastItem = $scope.temp.policy.settings.length-1;
260       $scope.temp.policy.settings.splice(lastItem);
261     };
262     
263     $scope.addNewTarget = function(){
264         $scope.temp.policy.yamlparams.targets.push('');
265     };
266     $scope.removeTarget = function(){
267         var lastItem = $scope.temp.policy.yamlparams.targets.length-1;
268         $scope.temp.policy.yamlparams.targets.splice(lastItem);
269     };
270     
271     $scope.addNewBL = function() {
272         $scope.temp.policy.yamlparams.blackList.push('');
273     };
274     
275     $scope.removeBL = function(id) {
276         $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){
277                         return obj !== id;
278                 });
279     };
280     
281     $scope.treatmentDatas = [{"treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices}];
282     $scope.addNewTreatment = function() {
283         $scope.temp.policy.rainyday.treatmentTableChoices.push({});
284     };
285     $scope.removeTreatment = function() {
286         var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length-1;
287         $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem);
288     };
289     
290         $scope.workstepDictionaryDatas = [];
291         $scope.getWorkstepValues = function(bbidValue){
292                 for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
293             var obj = $scope.rainyDayDictionaryDataEntity[i];
294             if (obj.bbid == bbidValue){
295                 $scope.workstepDictionaryDatas.push(obj.workstep);
296             }
297         }
298         };
299         
300         $scope.allowedTreatmentsDatas = [];
301         $scope.getTreatmentValues = function(bbidValue, workstepValue){
302                 for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
303             var obj = $scope.rainyDayDictionaryDataEntity[i];
304             if (obj.bbid == bbidValue && obj.workstep == workstepValue){
305                 var splitAlarm = obj.treatments.split(',');
306                 for (var j = 0; j < splitAlarm.length; ++j) {
307                         $scope.allowedTreatmentsDatas.push(splitAlarm[j]);
308                 }
309             }
310         }       
311         };
312     
313     $scope.ItemNo = 0;
314     $scope.ruleAlgorithmDatas = [{"ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices }];
315     
316     $scope.addNewRuleAlgorithm = function() {
317         if($scope.temp.policy.ruleAlgorithmschoices != null){
318                 var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length+1;
319         }else{
320                 var newItemNo = 1;
321         }
322         if(newItemNo > 1){
323                 var value = newItemNo-1;
324                 $scope.attributeDictionaryDatas.push('A'+value);
325         }
326         $scope.temp.policy.ruleAlgorithmschoices.push({'id':'A'+newItemNo});
327     };
328     
329     $scope.removeRuleAlgorithm = function() {
330       var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length-1;
331       $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
332     };
333     
334     $scope.providerListener = function(ruleProvider) {
335         if (ruleProvider!="Custom"){
336                 $scope.temp.policy.ruleAlgorithmschoices  = [];
337                 $scope.temp.policy.settings = [];
338                 $scope.temp.policy.attributes = [];
339         }
340     };
341     
342     $scope.importButton = true;
343     var fd;
344         $scope.uploadBLFile = function(files) {
345                 fd = new FormData();
346                 fd.append("file", files[0]);
347                 var fileExtension = files[0].name.split(".")[1];
348                 if(fileExtension == "xls"){
349                         $scope.importButton = false;
350                         $scope.$apply();
351                 }else{
352                         Notification.error("Upload the BlackList file which extends with .xls format.");
353                 }
354         };
355         
356         function arrayUnique(array) {
357             var a = array.concat();
358             for(var i=0; i<a.length; ++i) {
359                 for(var j=i+1; j<a.length; ++j) {
360                     if(a[i] === a[j])
361                         a.splice(j--, 1);
362                 }
363             }
364             return a;
365         }
366         
367         $scope.submitUpload = function(){
368                 $http.post("policycreation/importBlackListForDecisionPolicy", fd,  {
369                         withCredentials: false,
370                         headers: {'Content-Type': undefined},
371                         transformRequest: angular.identity
372                 }).success(function(data){
373                         $scope.data = JSON.parse(data.data);
374                         $scope.temp.policy.blackListEntries = $scope.data.blackListEntries;
375                         if($scope.temp.policy.blackListEntries[0] !== "error"){
376                                 $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
377                                 $scope.temp.policy.appendBlackListEntries = $scope.data.appendBlackListEntries;
378                                 $scope.blackListEntries = $scope.blackListEntries.filter(function (obj){
379                                         return !$scope.temp.policy.appendBlackListEntries.includes(obj);
380                                 });
381                                 if($scope.blackListEntries.length == 0){
382                                         $scope.validateButton = true;
383                                         Notification.error("Black Lists are empty. Minimum one entry required.");
384                                 }else{
385                                         $scope.temp.policy.blackListEntries = $scope.blackListEntries;
386                                         Notification.success("Blacklist File Uploaded Successfully.");
387                                         $scope.validateButton = false;
388                                         $scope.importButton = true;
389                                 }
390                         }else{
391                                  Notification.error("Blacklist File Upload Failed." + $scope.temp.policy.blackListEntries[1]);
392                         }
393                 }).error(function(data){
394                          Notification.error("Blacklist File Upload Failed.");
395                 });
396         };
397         
398         $scope.initializeBlackList = function(){
399                 if($scope.temp.policy.blackListEntryType === "Use File Upload"){
400                          $scope.validateButton = true;  
401                 } else {
402                          $scope.validateButton = false; 
403                 }
404                 $("#importFile").val('');
405         };
406         
407         $scope.exportBlackListEntries = function(){
408                 var uuu = "policycreation/exportDecisionBlackListEntries";
409                 var postData={policyData: $scope.temp.policy, date : $scope.temp.model.modifiedDate, version : $scope.temp.model.version};
410                 $.ajax({
411                         type : 'POST',
412                         url : uuu,
413                         dataType: 'json',
414                         contentType: 'application/json',
415                         data: JSON.stringify(postData),
416                         success : function(data){
417                                 $scope.$apply(function(){
418                                         $scope.data=data.data;
419                                         var url = '../' + $scope.data;
420                                         window.location = url;
421                                         Notification.success("BlackList Entries Exported Successfully.");
422                                 });
423                                 console.log($scope.data);
424                         },
425                         error : function(data){         
426                                 Notification.error("Error Occured while Exporting BlackList Entries.");
427                         }
428                 });
429         };      
430 }]);