E2E Automation
[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             function getAllFormId() {
42
43                     return Array.from(document.getElementsByClassName("formId"));
44             }
45             function searchActiveFormId() {
46
47                     var formArray = getAllFormId();
48                     for (var i = 0, max = formArray.length; i < max; i++) {
49                             console.log("Search active FormId, current element " + formArray[i].id);
50                             if (formArray[i].style.display !== "none") {
51                                     console.log("Active form is:" + formArray[i].id);
52                                     return formArray[i];
53                             }
54                     }
55                     console.log("No active formId found !");
56             }
57
58             function add_one_more() {
59
60                     console.log("add one more");
61                     $("#nav_Tabs li").removeClass("active");
62                     // FormSpan contains a block of the form that is not being
63                     // displayed. We will create clones of that and add them to tabs
64                     var form = $("#formSpan").clone(true, true)
65                     var count = 0;
66                     // Each new tab will have the formId class attached to it. This way
67                     // we can track how many forms we currently have out there and
68                     // assign listeners to them
69                     if ($(".formId").length > 0) {
70                             var greatest = 0;
71                             var s = $(".formId");
72                             for (var i = 0; i < s.length; i++) {
73                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
74                                             greatest = parseInt($(s[i]).attr("id").substring(6))
75                                     }
76                             }
77                             count = greatest + 1;
78                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
79                     } else {
80                             count++;
81                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
82                     }
83                     $("#add_one_more")
84                     .parent()
85                     .before(
86                     ' <li class="active"><a id="go_properties_tab'
87                     + count
88                     + '">new</a><button id="tab_close'
89                     + count
90                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
91                     $("#formId" + count).append(form.children());
92                     $(".formId").not($("#formId" + count)).css("display", "none");
93                     addCustListen(count);
94                     $("#formId" + count + " #id").val("new");
95                     return count;
96             }
97             function addCustListen(count) {
98
99                     $('#go_properties_tab' + count).click(function(event) {
100
101                             $("#nav_Tabs li").removeClass("active");
102                             $(this).parent().addClass("active");
103                             $("#formId" + count).css("display", "")
104                             $(".formId").not($("#formId" + count)).css("display", "none")
105                     })
106                     $('#tab_close' + count).click(function(event) {
107
108                             $(this).parent().remove();
109                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
110                             $("#formId" + count).remove();
111                     })
112             }
113             function greatestIdNum() {
114
115                     var greatest = 0;
116                     var s = $(".formId");
117                     for (var i = 0; i < s.length; i++) {
118                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
119                                     greatest = parseInt($(s[i]).attr("id").substring(6))
120                             }
121                     }
122                     return greatest;
123             }
124             function serializeElement(element) {
125
126                     var o = {};
127                     var a = element.serializeArray();
128                     $.each(a, function() {
129
130                             if (o[this.name]) {
131                                     if (!o[this.name].push) {
132                                             o[this.name] = [ o[this.name] ];
133                                     }
134                                     o[this.name].push(this.value || '');
135                             } else {
136                                     o[this.name] = this.value || '';
137                             }
138                     });
139                     return o;
140             }
141             function savePolicyLocally() {
142
143                     var polForm = {}
144                     polForm = serializeElement($("#operationalPolicyHeaderForm"));
145                     var policiesArray = []
146                     allPolicies['guard_policies'] = [];
147                     $.each($(".formId"), function() {
148
149                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
150                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
151                             policiesArray.push(policyProperties);
152                             // Now get the Guard
153                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
154                                     allPolicies['guard_policies'].push(serializeElement($("#" + this.id + " .guardProperties")));
155                             }
156                     });
157                     polForm['policies'] = policiesArray;
158                     allPolicies['operational_policy'] = polForm;
159             }
160             function add_new_policy() {
161
162                     console.log("add new policy");
163                     // remove old gui forms
164                     for (var i = 1; i < ($(".formId").length + 1); i++) {
165                             $("#go_properties_tab" + i).parent().remove();
166                     }
167                     $(".formId").remove();
168                     $("#add_one_more").click();
169             }
170             function configureComponents(allPolicies) {
171
172                     console.log("load properties to op policy");
173                     // Set the header
174                     $.each($('#operationalPolicyHeaderForm').find('.form-control'), function() {
175
176                             $(this).val(allPolicies['operational_policy'][this.id]);
177                     });
178                     // Set the sub-policies
179                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
180
181                             var formNum = add_one_more();
182                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
183
184                                     $("#formId"+formNum+" .policyProperties").find("#"+opPolicyPropValue.id).val(
185                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
186                             });
187                             // update the current tab label
188                             $("#go_properties_tab" + formNum).text(
189                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
190                             // Check if there is a guard set for it
191                             $.each(allPolicies['guard_policies'], function(guardElemIndex, guardElemValue) {
192
193                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
194                                             // Found one, set all guard prop
195                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,guardPropElemValue) {
196                                                 $("#formId"+formNum+" .guardProperties").find("#"+guardPropElemValue.id).val(
197                                                     allPolicies['guard_policies'][guardElemIndex][guardPropElemValue.id]);
198                                             });
199                                             // And finally enable the flag
200                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
201                                     }
202                             });
203                     });
204             }
205             
206             $scope.initTargetResourceId = function() {
207
208                         var recipe = $(event.target).val();
209
210                         var type = $(event.target).val();
211                         
212                         $("#modelName").val("");
213                         $("#modelInvariantId").val("");
214                         $("#modelVersionId").val("");
215                         $("#modelVersion").val("");
216                         $("#modelCustomizationId").val("");
217                         $('#resourceId').empty();
218                         $("#resourceId")
219                                         .append(
220                                                         $('<option></option>').val("")
221                                                                         .html(""));
222                         $("#resourceId").append(
223                                         $('<option></option>').val("Other:")
224                                                         .html("Other:"));
225                         if (type == "VM" || type == "" || type == "VNF" ) {
226                                 $("#metadata *").prop('disabled',true);
227                         }
228                         
229                         var resourceVnf = getResourceDetailsProperty();
230                         if (type == "VNF"
231                                         && (null !== resourceVnf || undefined !== resourceVnf)) {
232                                 for ( var prop in resourceVnf) {
233                                         var name = resourceVnf[prop]["name"];
234                                         $("#resourceId").append(
235                                                         $('<option></option>')
236                                                                         .val(name).html(name));
237                                 }
238
239                         }
240                         var resourceVfc = getResourceDetailsVfcProperty();
241                         if (type == "VFC"
242                                         && (null !== resourceVfc || undefined !== resourceVfc)) {
243                                 if (recipe == 'VF Module Create'
244                                                 || recipe == 'VF Module Delete') {
245                                         for ( var prop in resourceVfc) {
246                                                 if (resourceVfc[prop]["isBase"] == false) {
247                                                         var name = resourceVfc[prop]["name"];
248                                                         $("#resourceId").append(
249                                                                         $('<option></option>')
250                                                                                         .val(name)
251                                                                                         .html(name));
252                                                 }
253                                         }
254                                 } 
255                         else
256                         {
257                           for ( var prop in resourceVfc) {
258                                      var name = resourceVfc[prop]["name"];
259                               $("#resourceId").append(
260                                      $('<option></option>')
261                                             .val(name).html(name));
262                                         }
263                                         }
264                                 }
265             }   
266
267                 $scope.changeTargetResourceId = function() {
268                         $("#modelName").val("");
269                         $("#modelInvariantId").val("");
270                         $("#modelVersionId").val("");
271                         $("#modelVersion").val("");
272                         $("#modelCustomizationId").val("");
273                         var resourceVfc = getResourceDetailsVfcProperty();
274                         var type = $("#type").val();
275                         var recipe = $("#recipe").val();
276                         vfBaseName = $(event.target).val();
277                         if (type == "VFC"
278                                         && (null !== resourceVfc || undefined !== resourceVfc)
279                                         && (recipe == 'VF Module Create' || recipe == 'VF Module Delete')) {
280                                 for ( var prop in resourceVfc) {
281                                         var name = resourceVfc[prop]["name"];
282                                         if (name == vfBaseName) {
283                                                 var vfModuleModelName = resourceVfc[prop]["name"];
284                                                 $("#modelName").val(
285                                                                 vfModuleModelName);
286                                                 var vfModuleModelInvariantUUID = resourceVfc[prop]["invariantUUID"];
287                                                 $("#modelInvariantId").val(
288                                                                 vfModuleModelInvariantUUID);
289                                                 var vfModuleModelUUID = resourceVfc[prop]["UUID"];
290                                                 $("#modelVersionId").val(
291                                                                 vfModuleModelUUID);
292                                                 var vfModuleModelVersion = resourceVfc[prop]["version"];
293                                                 $("#modelVersion").val(
294                                                                 vfModuleModelVersion);
295                                                 var vfModuleModelCustomizationUUID = resourceVfc[prop]["customizationUUID"];
296                                                 $("#modelCustomizationId")
297                                                                 .val(
298                                                                                 vfModuleModelCustomizationUUID);
299                                         }
300                                 }
301                         }
302                         else {
303                                 $("#metadata *").prop('disabled',true);
304                         }
305                 }
306
307             $scope.changeGuardPolicyType = function() {
308
309                     var formItemActive = searchActiveFormId();
310                     if (formItemActive === undefined)
311                             return;
312                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
313                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
314                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
315                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
316                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
317                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
318                     }
319             }
320             $scope.initPolicySelect = function() {
321
322                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
323                             allPolicies = getOperationalPolicyProperty();
324                     }
325                     // Provision all policies ID first
326                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
327                             $.each(allPolicies['operational_policy']['policies'], function() {
328
329                                     $scope.policy_ids.push(this['id']);
330                             });
331                     }
332             }
333             $scope.init = function() {
334
335                     $(function() {
336                         $scope.clname=getLoopName();
337                             $("#add_one_more").click(function(event) {
338
339                                     console.log("add one more");
340                                     event.preventDefault();
341                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
342                             });
343                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
344                                     // load properties
345                                     console.log("load properties");
346                                     configureComponents(allPolicies);
347                             } else {
348                                     console.log("create new policy");
349                                     add_new_policy();
350                             }
351                             $("#savePropsBtn").click(function(event) {
352
353                                     console.log("save properties triggered");
354                                     savePolicyLocally();
355                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
356                                     $("#close_button").click();
357                             });
358                     });
359             }
360             $scope.init();
361             $scope.updateGuardRecipe = function(event) {
362
363                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
364                     // Get the second recipe (guard one) and update it
365                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
366             }
367             // When we change the name of a policy
368             $scope.updateTabLabel = function(event) {
369
370                     // update policy id structure
371                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
372                     $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
373                     $scope.policy_ids.push($(event.target).val());
374                     // Update the tab now
375                     $("#go_properties_tab" + formNum).text($(event.target).val());
376             }
377             $scope.close = function() {
378
379                     console.log("close");
380                     $uibModalInstance.close("closed");
381             };
382             $scope.submitForm = function(obj) {
383
384                     var operationalPolicies = getOperationalPolicies();
385                     if (obj !== null) {
386                             operationalPolicies[0]["configurationsJson"] = obj;
387                     }
388                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
389
390                             updateOpPolicyProperties(operationalPolicies);
391                     }, function(data) {
392
393                     });
394             };
395     } ]);