806cfea9d26fea68906611f3d5c1c3d4b844a6c0
[clamp.git] / src / main / resources / META-INF / resources / designer / scripts / OperationalPolicyCtrl.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2019 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             $scope.duplicated = false;
43
44             function getAllFormId() {
45
46                     return Array.from(document.getElementsByClassName("formId"));
47             }
48             function searchActiveFormId() {
49
50                     var formArray = getAllFormId();
51                     for (var i = 0, max = formArray.length; i < max; i++) {
52                             console.log("Search active FormId, current element " + formArray[i].id);
53                             if (formArray[i].style.display !== "none") {
54                                     console.log("Active form is:" + formArray[i].id);
55                                     return formArray[i];
56                             }
57                     }
58                     console.log("No active formId found !");
59             }
60             function add_one_more() {
61
62                     console.log("add one more");
63                     $("#nav_Tabs li").removeClass("active");
64                     // FormSpan contains a block of the form that is not being
65                     // displayed. We will create clones of that and add them to tabs
66                     var form = $("#formSpan").clone(true, true)
67                     var count = 0;
68                     // Each new tab will have the formId class attached to it. This way
69                     // we can track how many forms we currently have out there and
70                     // assign listeners to them
71                     if ($(".formId").length > 0) {
72                             var greatest = 0;
73                             var s = $(".formId");
74                             for (var i = 0; i < s.length; i++) {
75                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
76                                             greatest = parseInt($(s[i]).attr("id").substring(6))
77                                     }
78                             }
79                             count = greatest + 1;
80                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
81                     } else {
82                             count++;
83                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
84                     }
85                     $("#add_one_more")
86                     .parent()
87                     .before(
88                     ' <li class="active"><a id="go_properties_tab'
89                     + count
90                     + '">new</a><button id="tab_close'
91                     + count
92                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
93                     $("#formId" + count).append(form.children());
94                     $(".formId").not($("#formId" + count)).css("display", "none");
95                     addCustListen(count);
96                     $("#formId" + count + " #id").val("new");
97                     $("#formId" + count + " #clname").val($scope.clname);
98                     return count;
99             }
100             function addCustListen(count) {
101
102                     $('#go_properties_tab' + count).click(function(event) {
103
104                             $("#nav_Tabs li").removeClass("active");
105                             $(this).parent().addClass("active");
106                             $("#formId" + count).css("display", "")
107                             $(".formId").not($("#formId" + count)).css("display", "none")
108                     })
109                     $('#tab_close' + count).click(function(event) {
110
111                             $(this).parent().remove();
112                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
113                             $("#formId" + count).remove();
114                     })
115             }
116             function greatestIdNum() {
117
118                     var greatest = 0;
119                     var s = $(".formId");
120                     for (var i = 0; i < s.length; i++) {
121                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
122                                     greatest = parseInt($(s[i]).attr("id").substring(6))
123                             }
124                     }
125                     return greatest;
126             }
127             function serializeElement(element) {
128
129                     var o = {};
130                     var a = element.serializeArray();
131                     $.each(a, function() {
132
133                             if (o[this.name]) {
134                                     if (!o[this.name].push) {
135                                             o[this.name] = [ o[this.name] ];
136                                     }
137                                     o[this.name].push(this.value || '');
138                             } else {
139                                     o[this.name] = this.value || '';
140                             }
141                     });
142                     return o;
143             }
144             function savePolicyLocally() {
145
146                     var polForm = {};
147                     var clPolForm = {};
148                     clPolForm = serializeElement($("#operationalPolicyHeaderForm"));
149                     allPolicies['guard_policies'] = {};
150                     var policiesArray = []
151                     $.each($(".formId"), function() {
152
153                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
154                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
155                             policiesArray.push(policyProperties);
156                             // Now get the Guard
157                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
158                                     var guardPolicyBody = serializeElement($("#" + this.id + " .guardProperties"));
159                                     var guardPolicyId = guardPolicyBody['id'];
160                                     delete guardPolicyBody['id'];
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                             $(this).val(allPolicies['operational_policy']['controlLoop'][this.id]);
185                     });
186                     // Set the sub-policies
187                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
188
189                             var formNum = add_one_more();
190                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
191
192                                     $("#formId" + formNum + " .policyProperties").find("#" + opPolicyPropValue.id).val(
193                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
194                             });
195
196                             // Initial TargetResourceId options
197                             initTargetResourceIdOptions(allPolicies['operational_policy']['policies'][opPolicyElemIndex]['target']['type'], formNum);
198                             $.each($('.policyTarget').find('.form-control'), function(opPolicyTargetPropIndex, opPolicyTargetPropValue) {
199
200                                     $("#formId" + formNum + " .policyTarget").find("#" + opPolicyTargetPropValue.id).val(
201                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex]['target'][opPolicyTargetPropValue.id]);
202                             });
203
204                             // update the current tab label
205                             $("#go_properties_tab" + formNum).text(
206                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
207                             // Check if there is a guard set for it
208                             $.each(allPolicies['guard_policies'], function(guardElemId, guardElemValue) {
209
210                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
211                                             // Found one, set all guard prop
212                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,
213                                                                                                          guardPropElemValue) {
214
215                                                     guardElemValue['id'] = guardElemId;
216                                                     $("#formId" + formNum + " .guardProperties").find("#" + guardPropElemValue.id).val(
217                                                     guardElemValue[guardPropElemValue.id]);
218                                             });
219                                             iniGuardPolicyType(guardElemId, formNum);
220                                             // And finally enable the flag
221                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
222                                     }
223                             });
224                     });
225             }
226             function iniGuardPolicyType (guardPolicyId, formNum) {
227                     if(guardPolicyId.indexOf('guard.minmax.') !== -1) {
228                                 $("#formId" + formNum + " #minMaxGuardPolicyDiv").show();
229                                 $("#formId" + formNum + " #frequencyLimiterGuardPolicyDiv").hide();
230                                 $("#formId" + formNum + " #guardPolicyType").val("GUARD_MIN_MAX");
231                     } else if (guardPolicyId.indexOf('guard.frequency.') !== -1) {
232                         $("#formId" + formNum + " #minMaxGuardPolicyDiv").hide();
233                             $("#formId" + formNum + " #frequencyLimiterGuardPolicyDiv").show();
234                             $("#formId" + formNum + " #guardPolicyType").val("GUARD_YAML");
235                     }
236             }
237             function initTargetResourceIdOptions (targetType, formNum) {
238                     var recipe = $("#formId" + formNum + "#recipe").val();
239                     $("#formId" + formNum + " #resourceID").empty();
240                     $("#formId" + formNum + " #resourceID").append($('<option></option>').val("").html("-- choose an option --"));
241
242                     var resourceVnf = getResourceDetailsVfProperty();
243                     if (targetType == "VNF" && (null !== resourceVnf || undefined !== resourceVnf)) {
244                             for ( var prop in resourceVnf) {
245                                     var name = resourceVnf[prop]["name"];
246                                     $("#formId" + formNum + " #resourceID").append($('<option></option>').val(name).html(name));
247                             }
248                     }
249                     var resourceVFModule = getResourceDetailsVfModuleProperty();
250                     if (targetType == "VFMODULE" && (null !== resourceVFModule || undefined !== resourceVFModule)) {
251                             if (recipe == 'VF Module Create' || recipe == 'VF Module Delete') {
252                                     for ( var prop in resourceVFModule) {
253                                             if (resourceVFModule[prop]["isBase"] == false) {
254                                                     $("#formId" + formNum + " #resourceID").append($('<option></option>').val(resourceVFModule[prop]["vfModuleModelName"]).html(resourceVFModule[prop]["vfModuleModelName"]));
255                                             }
256                                     }
257                             } else {
258                                     for ( var prop in resourceVFModule) {
259                                             $("#formId" + formNum + " #resourceID").append($('<option></option>').val(resourceVFModule[prop]["vfModuleModelName"]).html(resourceVFModule[prop]["vfModuleModelName"]));
260                                     }
261                             }
262                     }
263             }
264
265             function initTargetModelAttributes (formNum) {
266                     $("#formId" + formNum + " #modelName").val("");
267                     $("#formId" + formNum + " #modelInvariantId").val("");
268                     $("#formId" + formNum + " #modelVersionId").val("");
269                     $("#formId" + formNum + " #modelVersion").val("");
270                     $("#formId" + formNum + " #modelCustomizationId").val("");
271             }
272
273             $scope.initTargetResourceId = function(event) {
274                 var formNum = $(event.target).closest('.formId').attr('id').substring(6);
275                 initTargetModelAttributes(formNum);
276                     var type = $(event.target).val();
277                     initTargetResourceIdOptions(type, formNum);
278             }
279
280             $scope.changeGuardId = function(formItemActive) {
281                     if (formItemActive === undefined) {
282                             formItemActive = searchActiveFormId();
283                             if (formItemActive === undefined) {
284                                 return;
285                             }
286                     }
287                     var oldValue = $("#" + formItemActive.id + " .guardProperties #id").val();
288                     // remove old prefix
289                     if(oldValue.indexOf('guard.minmax.') !== -1) {
290                         oldValue = oldValue.substr(oldValue.indexOf('guard.minmax.') + 13);
291                     } else if (oldValue.indexOf('guard.frequency.') !== -1) {
292                         oldValue = oldValue.substr(oldValue.indexOf('guard.frequency.') + 16);
293                     }
294
295                     var prefix = "guard.";
296                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
297                         prefix = prefix + "minmax.";
298                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
299                         prefix = prefix + "frequency.";
300                     }
301                     $("#" + formItemActive.id + " .guardProperties #id").val(prefix+oldValue);
302             }
303
304             $scope.changeTargetResourceId = function(event) {
305                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
306                     initTargetModelAttributes(formNum);
307
308                     var resourceVFModule = getResourceDetailsVfModuleProperty();
309                     var type = $("#formId" + formNum +" #type").val();
310                     var recipe = $("#formId" + formNum +" #recipe").val();
311                     if (type == "VFMODULE" && (null !== resourceVFModule || undefined !== resourceVFModule)
312                     && (recipe == 'VF Module Create' || recipe == 'VF Module Delete')) {
313                             for ( var prop in resourceVFModule) {
314                                     if (prop ==  $(event.target).val()) {
315                                             $("#formId" + formNum +" #modelName").val(resourceVFModule[prop]["vfModuleModelName"]);
316                                             $("#formId" + formNum +" #modelInvariantId").val(resourceVFModule[prop]["vfModuleModelInvariantUUID"]);
317                                             $("#formId" + formNum +" #modelVersionId").val(resourceVFModule[prop]["vfModuleModelUUID"]);
318                                             $("#formId" + formNum +" #modelVersion").val(resourceVFModule[prop]["vfModuleModelVersion"]);
319                                             $("#formId" + formNum +" #modelCustomizationId").val(resourceVFModule[prop]["vfModuleModelCustomizationUUID"]);
320                                             $("#formId" + formNum +" #metadata *").prop('disabled', false);
321                                     }
322                             }
323                     } else {
324                             $("#formId" + formNum +" #metadata *").prop('disabled', true);
325                     }
326             }
327             $scope.changeGuardPolicyType = function() {
328
329                     var formItemActive = searchActiveFormId();
330                     if (formItemActive === undefined)
331                             return;
332                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
333                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
334                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
335                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
336                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
337                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
338                     }
339                     $scope.changeGuardId(formItemActive);
340             }
341             $scope.initPolicySelect = function() {
342
343                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
344                             allPolicies = getOperationalPolicyProperty();
345                     }
346                     // Provision all policies ID first
347                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
348                             $.each(allPolicies['operational_policy']['policies'], function() {
349
350                                     $scope.policy_ids.push(this['id']);
351                             });
352                     }
353             }
354             $scope.init = function() {
355
356                     $(function() {
357
358                             $scope.clname = getLoopName();
359                             $("#add_one_more").click(function(event) {
360
361                                     console.log("add one more");
362                                     event.preventDefault();
363                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
364                             });
365                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
366                                     // load properties
367                                     console.log("load properties");
368                                     configureComponents(allPolicies);
369                             } else {
370                                     console.log("create new policy");
371                                     add_new_policy();
372                             }
373                             $("#savePropsBtn").click(function(event) {
374
375                                     console.log("save properties triggered");
376                                     savePolicyLocally();
377                                     for (var i = 0; i <= $scope.guard_ids.length; i++) {
378                                             for (var j = i; j <= $scope.guard_ids.length; j++) {
379                                                     if (i != j && $scope.guard_ids[i] == $scope.guard_ids[j]) {
380                                                             // duplacated guard policy id exist
381                                                             alert("The guard policy ID should be unique.");
382                                                             return;
383                                                     }
384                                             }
385                                     }
386                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
387                                     $("#close_button").click();
388                             });
389                     });
390             }
391             $scope.init();
392             $scope.updateGuardRecipe = function(event) {
393
394                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
395                     // Get the second recipe (guard one) and update it
396                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
397             }
398             $scope.updateGuardActor = function(event) {
399
400                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
401                     // Get the second actor (guard one) and update it
402                     $($("#formId" + formNum + " #actor")[1]).val($(event.target).val());
403             }
404             // When we change the name of a policy
405                 $scope.updateTabLabel = function (event) {
406
407                         // update policy id structure
408                         var formNum = $(event.target).closest('.formId').attr('id').substring(6);
409                         var policyId = $(event.target).val();
410                         if ($scope.policy_ids.includes(policyId)) {
411                                 console.log("Duplicated ID, cannot proceed");
412                                 $scope.duplicated = true;
413                         } else {
414                                 $scope.duplicated = false;
415                                 $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
416                                 $scope.policy_ids.push($(event.target).val());
417                                 // Update the tab now
418                                 $("#go_properties_tab" + formNum).text($(event.target).val());
419                         }
420                 };
421             $scope.close = function() {
422
423                     console.log("close");
424                     $uibModalInstance.close("closed");
425             };
426             $scope.submitForm = function(obj) {
427
428                     var operationalPolicies = getOperationalPolicies();
429                     if (obj !== null) {
430                             operationalPolicies[0]["configurationsJson"] = obj;
431                     }
432                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
433
434                             updateOpPolicyProperties(operationalPolicies);
435                     }, function(data) {
436
437                     });
438             };
439     } ]);