4e8855eb0cd1eb3f43fb20f22c3828186d6c2ade
[clamp.git] / src / main / resources / META-INF / resources / designer / scripts / OperationalPolicyCtrl.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License"); 
9  * you may not use this file except in compliance with the License. 
10  * You may obtain a copy of the License at
11  * 
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software 
15  * distributed under the License is distributed on an "AS IS" BASIS, 
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
17  * See the License for the specific language governing permissions and 
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * 
22  */
23 app
24 .controller(
25 'operationalPolicyCtrl',
26 [
27     '$scope',
28     '$rootScope',
29     '$uibModalInstance',
30     'data',
31     'operationalPolicyService',
32     'dialogs',
33     function($scope, $rootScope, $uibModalInstance, data, operationalPolicyService, dialogs) {
34
35             console.log("//////operationalPolicyCtrl");
36             $scope.policy_ids = []
37             var allPolicies = {};
38             $scope.guardType = "GUARD_MIN_MAX";
39             $scope.number = 0;
40             $scope.clname = "";
41             $scope.guard_ids = [];
42             function getAllFormId() {
43
44                     return Array.from(document.getElementsByClassName("formId"));
45             }
46             function searchActiveFormId() {
47
48                     var formArray = getAllFormId();
49                     for (var i = 0, max = formArray.length; i < max; i++) {
50                             console.log("Search active FormId, current element " + formArray[i].id);
51                             if (formArray[i].style.display !== "none") {
52                                     console.log("Active form is:" + formArray[i].id);
53                                     return formArray[i];
54                             }
55                     }
56                     console.log("No active formId found !");
57             }
58
59             function add_one_more() {
60
61                     console.log("add one more");
62                     $("#nav_Tabs li").removeClass("active");
63                     // FormSpan contains a block of the form that is not being
64                     // displayed. We will create clones of that and add them to tabs
65                     var form = $("#formSpan").clone(true, true)
66                     var count = 0;
67                     // Each new tab will have the formId class attached to it. This way
68                     // we can track how many forms we currently have out there and
69                     // assign listeners to them
70                     if ($(".formId").length > 0) {
71                             var greatest = 0;
72                             var s = $(".formId");
73                             for (var i = 0; i < s.length; i++) {
74                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
75                                             greatest = parseInt($(s[i]).attr("id").substring(6))
76                                     }
77                             }
78                             count = greatest + 1;
79                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
80                     } else {
81                             count++;
82                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
83                     }
84                     $("#add_one_more")
85                     .parent()
86                     .before(
87                     ' <li class="active"><a id="go_properties_tab'
88                     + count
89                     + '">new</a><button id="tab_close'
90                     + count
91                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
92                     $("#formId" + count).append(form.children());
93                     $(".formId").not($("#formId" + count)).css("display", "none");
94                     addCustListen(count);
95                     $("#formId" + count + " #id").val("new");
96                     $("#formId" + count + " #clname").val($scope.clname);
97                     return count;
98             }
99             function addCustListen(count) {
100
101                     $('#go_properties_tab' + count).click(function(event) {
102
103                             $("#nav_Tabs li").removeClass("active");
104                             $(this).parent().addClass("active");
105                             $("#formId" + count).css("display", "")
106                             $(".formId").not($("#formId" + count)).css("display", "none")
107                     })
108                     $('#tab_close' + count).click(function(event) {
109
110                             $(this).parent().remove();
111                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
112                             $("#formId" + count).remove();
113                     })
114             }
115             function greatestIdNum() {
116
117                     var greatest = 0;
118                     var s = $(".formId");
119                     for (var i = 0; i < s.length; i++) {
120                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
121                                     greatest = parseInt($(s[i]).attr("id").substring(6))
122                             }
123                     }
124                     return greatest;
125             }
126             function serializeElement(element) {
127
128                     var o = {};
129                     var a = element.serializeArray();
130                     $.each(a, function() {
131
132                             if (o[this.name]) {
133                                     if (!o[this.name].push) {
134                                             o[this.name] = [ o[this.name] ];
135                                     }
136                                     o[this.name].push(this.value || '');
137                             } else {
138                                     o[this.name] = this.value || '';
139                             }
140                     });
141                     return o;
142             }
143             function savePolicyLocally() {
144
145                     var polForm = {};
146                     var clPolForm = {};
147                     clPolForm = serializeElement($("#operationalPolicyHeaderForm"));
148                     allPolicies['guard_policies'] = {};
149                     var policiesArray = []
150                     $.each($(".formId"), function() {
151
152                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
153                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
154                             policiesArray.push(policyProperties);
155                             // Now get the Guard
156                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
157                                 var guardPolicyBody = serializeElement($("#" + this.id + " .guardProperties"));
158                                 var guardPolicyId = guardPolicyBody['id'];
159                                 delete guardPolicyBody['id'];
160
161                                     allPolicies['guard_policies'][guardPolicyId] = guardPolicyBody;
162                                     $scope.guard_ids.push(guardPolicyId);
163                             }
164                     });
165                     polForm['controlLoop'] = clPolForm;
166                     polForm['policies'] = policiesArray;
167                     allPolicies['operational_policy'] = polForm;
168             }
169             function add_new_policy() {
170
171                     console.log("add new policy");
172                     // remove old gui forms
173                     for (var i = 1; i < ($(".formId").length + 1); i++) {
174                             $("#go_properties_tab" + i).parent().remove();
175                     }
176                     $(".formId").remove();
177                     $("#add_one_more").click();
178             }
179             function configureComponents(allPolicies) {
180
181                     console.log("load properties to op policy");
182                     // Set the header
183                     $.each($('#operationalPolicyHeaderForm').find('.form-control'), function() {
184
185                             $(this).val(allPolicies['operational_policy']['controlLoop'][this.id]);
186                     });
187                     // Set the sub-policies
188                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
189
190                             var formNum = add_one_more();
191                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
192
193                                     $("#formId"+formNum+" .policyProperties").find("#"+opPolicyPropValue.id).val(
194                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
195                             });
196                             // update the current tab label
197                             $("#go_properties_tab" + formNum).text(
198                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
199                             // Check if there is a guard set for it
200                             $.each(allPolicies['guard_policies'], function(guardElemId, guardElemValue) {
201
202                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
203                                             // Found one, set all guard prop
204                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,guardPropElemValue) {
205                                                 guardElemValue['id'] = guardElemId;
206                                                 $("#formId"+formNum+" .guardProperties").find("#"+guardPropElemValue.id).val(
207                                                     guardElemValue[guardPropElemValue.id]);
208                                             });
209                                             // And finally enable the flag
210                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
211                                     }
212                             });
213                     });
214             }
215             
216             $scope.initTargetResourceId = function() {
217
218                         var recipe = $(event.target).val();
219
220                         var type = $(event.target).val();
221                         
222                         $("#modelName").val("");
223                         $("#modelInvariantId").val("");
224                         $("#modelVersionId").val("");
225                         $("#modelVersion").val("");
226                         $("#modelCustomizationId").val("");
227                         $('#resourceId').empty();
228                         $("#resourceId")
229                                         .append(
230                                                         $('<option></option>').val("")
231                                                                         .html(""));
232                         $("#resourceId").append(
233                                         $('<option></option>').val("Other:")
234                                                         .html("Other:"));
235                         if (type == "VM" || type == "" || type == "VNF" ) {
236                                 $("#metadata *").prop('disabled',true);
237                         }
238                         
239                         var resourceVnf = getResourceDetailsProperty();
240                         if (type == "VNF"
241                                         && (null !== resourceVnf || undefined !== resourceVnf)) {
242                                 for ( var prop in resourceVnf) {
243                                         var name = resourceVnf[prop]["name"];
244                                         $("#resourceId").append(
245                                                         $('<option></option>')
246                                                                         .val(name).html(name));
247                                 }
248
249                         }
250                         var resourceVfc = getResourceDetailsVfcProperty();
251                         if (type == "VFC"
252                                         && (null !== resourceVfc || undefined !== resourceVfc)) {
253                                 if (recipe == 'VF Module Create'
254                                                 || recipe == 'VF Module Delete') {
255                                         for ( var prop in resourceVfc) {
256                                                 if (resourceVfc[prop]["isBase"] == false) {
257                                                         var name = resourceVfc[prop]["name"];
258                                                         $("#resourceId").append(
259                                                                         $('<option></option>')
260                                                                                         .val(name)
261                                                                                         .html(name));
262                                                 }
263                                         }
264                                 } 
265                         else
266                         {
267                           for ( var prop in resourceVfc) {
268                                      var name = resourceVfc[prop]["name"];
269                               $("#resourceId").append(
270                                      $('<option></option>')
271                                             .val(name).html(name));
272                                         }
273                                         }
274                                 }
275             }   
276
277                 $scope.changeTargetResourceId = function() {
278                         $("#modelName").val("");
279                         $("#modelInvariantId").val("");
280                         $("#modelVersionId").val("");
281                         $("#modelVersion").val("");
282                         $("#modelCustomizationId").val("");
283                         var resourceVfc = getResourceDetailsVfcProperty();
284                         var type = $("#type").val();
285                         var recipe = $("#recipe").val();
286                         vfBaseName = $(event.target).val();
287                         if (type == "VFC"
288                                         && (null !== resourceVfc || undefined !== resourceVfc)
289                                         && (recipe == 'VF Module Create' || recipe == 'VF Module Delete')) {
290                                 for ( var prop in resourceVfc) {
291                                         var name = resourceVfc[prop]["name"];
292                                         if (name == vfBaseName) {
293                                                 var vfModuleModelName = resourceVfc[prop]["name"];
294                                                 $("#modelName").val(
295                                                                 vfModuleModelName);
296                                                 var vfModuleModelInvariantUUID = resourceVfc[prop]["invariantUUID"];
297                                                 $("#modelInvariantId").val(
298                                                                 vfModuleModelInvariantUUID);
299                                                 var vfModuleModelUUID = resourceVfc[prop]["UUID"];
300                                                 $("#modelVersionId").val(
301                                                                 vfModuleModelUUID);
302                                                 var vfModuleModelVersion = resourceVfc[prop]["version"];
303                                                 $("#modelVersion").val(
304                                                                 vfModuleModelVersion);
305                                                 var vfModuleModelCustomizationUUID = resourceVfc[prop]["customizationUUID"];
306                                                 $("#modelCustomizationId")
307                                                                 .val(
308                                                                                 vfModuleModelCustomizationUUID);
309                                         }
310                                 }
311                         }
312                         else {
313                                 $("#metadata *").prop('disabled',true);
314                         }
315                 }
316
317             $scope.changeGuardPolicyType = function() {
318
319                     var formItemActive = searchActiveFormId();
320                     if (formItemActive === undefined)
321                             return;
322                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
323                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
324                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
325                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
326                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
327                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
328                     }
329             }
330             $scope.initPolicySelect = function() {
331
332                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
333                             allPolicies = getOperationalPolicyProperty();
334                     }
335                     // Provision all policies ID first
336                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
337                             $.each(allPolicies['operational_policy']['policies'], function() {
338
339                                     $scope.policy_ids.push(this['id']);
340                             });
341                     }
342             }
343             $scope.init = function() {
344
345                     $(function() {
346                         $scope.clname=getLoopName();
347                             $("#add_one_more").click(function(event) {
348
349                                     console.log("add one more");
350                                     event.preventDefault();
351                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
352                             });
353                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
354                                     // load properties
355                                     console.log("load properties");
356                                     configureComponents(allPolicies);
357                             } else {
358                                     console.log("create new policy");
359                                     add_new_policy();
360                             }
361                             $("#savePropsBtn").click(function(event) {
362                                     console.log("save properties triggered");
363                                     savePolicyLocally();
364                                 for(var i = 0; i <= $scope.guard_ids.length; i++) {
365                                     for(var j = i; j <= $scope.guard_ids.length; j++) {
366                                         if(i != j && $scope.guard_ids[i] == $scope.guard_ids[j]) {
367                                             // duplacated guard policy id exist
368                                                 alert("The guard policy ID should be unique.");
369                                                 return;
370                                         }
371                                     }
372                                 }
373                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
374                                     $("#close_button").click();
375                             });
376                     });
377             }
378             $scope.init();
379             $scope.updateGuardRecipe = function(event) {
380
381                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
382                     // Get the second recipe (guard one) and update it
383                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
384             }
385             $scope.updateGuardActor = function(event) {
386
387                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
388                     // Get the second actor (guard one) and update it
389                     $($("#formId" + formNum + " #actor")[1]).val($(event.target).val());
390             }
391             // When we change the name of a policy
392             $scope.updateTabLabel = function(event) {
393
394                     // update policy id structure
395                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
396                     $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
397                     $scope.policy_ids.push($(event.target).val());
398                     // Update the tab now
399                     $("#go_properties_tab" + formNum).text($(event.target).val());
400             }
401             $scope.close = function() {
402
403                     console.log("close");
404                     $uibModalInstance.close("closed");
405             };
406             $scope.submitForm = function(obj) {
407
408                     var operationalPolicies = getOperationalPolicies();
409                     if (obj !== null) {
410                             operationalPolicies[0]["configurationsJson"] = obj;
411                     }
412                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
413
414                             updateOpPolicyProperties(operationalPolicies);
415                     }, function(data) {
416
417                     });
418             };
419     } ]);