d607a49d82f5713295cb9babeae561d7434e90ec
[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             var parent_policy = {}
37             var policy_ids = {}
38             var loadingId = false;
39             var allPolicies = {};
40             var allPolIds = [];
41             
42             $scope.guardType="GUARD_MIN_MAX";
43             $scope.targetResource="";
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 initTargetResourceId() {
61
62                     if (vf_Services !== null && vf_Services !== undefined) {
63                             // Set all the Resource Invariant UUID in the target resource ID
64                             // list (+Empty and other)
65                             Object.keys(vf_Services["shared"]["byVf"]).forEach(function(key) {
66
67                                     $("#targetResourceId").append($('<option></option>').val(key).html(key));
68                             });
69                     }
70             }
71             // load recipes for a chosen policy
72             function disperseConfig(policyObj, id) {
73
74                     console.log("disperseConfig with id:" + id);
75                     parent_policy = {};
76                     // remove old gui forms
77                     for (var i = 1; i < ($(".formId").length + 1); i++) {
78                             $("#go_properties_tab" + i).parent().remove();
79                     }
80                     $(".formId").remove();
81                     if (policyObj !== undefined && policyObj[id] !== undefined) {
82                             var el = policyObj[id][3]['policyConfigurations']
83                             for (var i = 0; i < el.length; i++) {
84                                     loadingId = true;
85                                     var num = add_one_more();
86                                     console.log("number is=:" + num);
87                                     loadingId = false;
88                                     for (var j = 0; j < el[i].length; j++) {
89                                             console.log("attr:" + el[i][j].name + "; value is:" + el[i][j].value);
90                                             if (el[i][j].hasOwnProperty("name")) {
91                                                     $("#formId" + num + " #" + el[i][j].name).val(el[i][j].value);
92                                                     if (el[i][j].name === "_id") {
93                                                             console.log("formId num:" + num + "; value is:" + el[i][j].value);
94                                                             policy_ids["#formId" + num] = el[i][j].value
95                                                     }
96                                                     if (el[i][j].name === 'parentPolicy')
97                                                             parent_policy[num] = el[i][j].value
98                                                     if (el[i][j].name === 'recipe' && el[i][j].value.toString() !== '') {
99                                                             $("#go_properties_tab" + num).text(el[i][j].value)
100                                                     }
101                                                     if (el[i][j].name === "targetResourceIdOther" && el[i][j].value.toString() !== '') {
102                                                             // Add the entry and set it
103                                                             $("#formId" + num + " #targetResourceId").append(
104                                                             $('<option></option>').val($("#formId" + num + " #targetResourceIdOther").val()).html(
105                                                             $("#formId" + num + " #targetResourceIdOther").val()));
106                                                             $("#formId" + num + " #targetResourceId").val(
107                                                             $("#formId" + num + " #targetResourceIdOther").val());
108                                                     }
109                                                     $scope.changeGuardPolicyType();
110                                             }
111                                     }
112                             }
113                             // Adding all the ids for parent policy options
114                             for (var i = 1; i <= $(".formId").length; i++) {
115                                     for (k in policy_ids) {
116                                             if ($("#formId" + i + " #_id").val() !== policy_ids[k].toString()
117                                             && $(k + " #recipe").val() !== undefined && $(k + " #recipe").val() !== "") {
118                                                     $("#formId" + i + " #parentPolicy").append(
119                                                     "<option value=\"" + policy_ids[k] + "\">" + $(k + " #recipe").val() + "</option>");
120                                             }
121                                     }
122                             }
123                             for (k in parent_policy) {
124                                     $("#formId" + k + " #parentPolicy").val(parent_policy[k]);
125                                     if ($("#formId" + k + " #parentPolicy").val() == "") {
126                                             $("#formId" + k + " #parentPolicyConditions").multiselect("disable");
127                                     } else {
128                                             $("#formId" + k + " #parentPolicyConditions").multiselect("enable");
129                                     }
130                                     // force the change event
131                                     $("#formId" + k + " #parentPolicy").change();
132                             }
133                             // Now load all component with the right value defined in
134                             // policyObj JSON
135                             for (headInd in policyObj[id]) {
136                                     if (!(policyObj[id][headInd].hasOwnProperty("policyConfigurations"))) {
137                                             $("#" + policyObj[id][headInd].name).val(policyObj[id][headInd].value);
138                                     }
139                             }
140                     }
141                     setMultiSelect();
142                     if (readMOnly) {
143                             $('select[multiple] option').each(function() {
144
145                                     var input = $('input[value="' + $(this).val() + '"]');
146                                     input.prop('disabled', true);
147                                     input.parent('li').addClass('disabled');
148                             });
149                             $('input[value="multiselect-all"]').prop('disabled', true).parent('li').addClass('disabled');
150                     }
151             }
152             function addSelectListen(count) {
153
154                     var onSelectChange = function() {
155
156                             var opselected = this.selectedOptions[0].text;
157                             if (this.id == "recipe") {
158                                     if (opselected !== "") {
159                                             var polCount = $(this).closest("[id^='formId']").attr("id").substring(6);
160                                             $(this).closest(".policyPanel").find("#go_properties_tab" + polCount).text(opselected);
161                                     } else {
162                                             $(this).closest("[id^='go_properties_tab']").text("Policy");
163                                     }
164                             }
165                             if (this.id == "parentPolicy") {
166                                     var ppCond = $(this).closest("[id^='formId']").find("#parentPolicyConditions");
167                                     if (opselected == "") {
168                                             ppCond.multiselect("clearSelection");
169                                             ppCond.multiselect("disable");
170                                     } else {
171                                             ppCond.multiselect("enable");
172                                     }
173                             }
174                     };
175                     $("#formId" + count + " select").each(function() {
176
177                             this.change = onSelectChange;
178                     });
179             }
180             // This is ensure there are no repeated keys in the map
181             function noRepeats(form) {
182
183                     // triggered per policy.
184                     var select = {};
185                     for (var i = 0; i < form.length; i++) {
186                             if (select[form[i].name] === undefined)
187                                     select[form[i].name] = []
188                             select[form[i].name].push(form[i].value);
189                     }
190                     var arr = []
191                     for (s in select) {
192                             var f = {}
193                             f.name = s
194                             f.value = select[s]
195                             arr.push(f)
196                     }
197                     return arr
198             }
199             function add_one_more() {
200
201                     console.log("add one more");
202                     setPolicyOptions();
203                     $("#nav_Tabs li").removeClass("active");
204                     // FormSpan contains a block of the form that is not being
205                     // displayed. We will create clones of that and add them to tabs
206                     var form = $($("#formSpan").children()[0]).clone()
207                     var count = 0;
208                     // Each new tab will have the formId class attached to it. This way
209                     // we can track how many forms we currently have out there and
210                     // assign listeners to them
211                     if ($(".formId").length > 0) {
212                             var greatest = 0;
213                             var s = $(".formId");
214                             for (var i = 0; i < s.length; i++) {
215                                     if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
216                                             greatest = parseInt($(s[i]).attr("id").substring(6))
217                                     }
218                             }
219                             count = greatest + 1;
220                             $("#properties_tab").append(('<span class="formId" id="formId' + count + '"></span>'));
221                     } else {
222                             count++;
223                             $("#properties_tab").append('<span class="formId" id="formId1"></span>');
224                     }
225                     // $(form).find("#policyName").val("Recipe "+makid(2))
226                     // TODO change up how we auto assign policyName. There could be the
227                     // case where we do this and it will have repeats
228                     // alert($(form).find("#_id").val())
229                     // policyNameChangeListener(form)
230                     $("#add_one_more")
231                     .parent()
232                     .before(
233                     ' <li class="active"><a id="go_properties_tab'
234                     + count
235                     + '">Policy</a><button id="tab_close'
236                     + count
237                     + '" type="button" class="close tab-close-popup" aria-hidden="true" style="margin-top: -30px;margin-right: 5px">&times;</button></li>');
238                     $("#formId" + count).append(form);
239                     $(".formId").not($("#formId" + count)).css("display", "none")
240                     addCustListen(count)
241                     addSelectListen(count);
242                     // This is for when the process is not loading from map but being
243                     // created
244                     if (!loadingId) {
245                             var l = makeid()
246                             $(form).find("#_id").val(l)
247                             policy_ids["#formId" + count] = l
248                             var answers = {}
249                             for (var i = 1; i <= greatestIdNum(); i++) {
250                                     if ($("#formId" + i).length > 0) {
251                                             answers["#formId" + i + " #parentPolicy"] = $("#formId" + i + " #parentPolicy").val();
252                                             $("#formId" + i + " #parentPolicy").empty();
253                                             for (k in policy_ids) {
254                                                     if (($("#formId" + i + " #_id").val() !== policy_ids[k].toString())
255                                                     && $(k + " #recipe").val() !== undefined && $(k + " #recipe").val() !== "") {
256                                                             $("#formId" + i + " #parentPolicy").append(
257                                                             "<option value='" + policy_ids[k] + "'>" + $(k + " #recipe").val() + "</option>")
258                                                     }
259                                             }
260                                             $("#formId" + i + " #parentPolicy").prepend("<option value=''></option>")
261                                     }
262                             }
263                             $("#formId" + count + " #parentPolicyConditions").multiselect("disable");
264                             // re-populate parent policy with chosen options
265                             for (k in answers) {
266                                     $(k).val(answers[k])
267                             }
268                     }
269                     return count;
270             }
271             function addCustListen(count) {
272
273                     $('#go_properties_tab' + count).click(function(event) {
274
275                             $("#nav_Tabs li").removeClass("active");
276                             $(this).parent().addClass("active");
277                             $("#formId" + count).css("display", "")
278                             $(".formId").not($("#formId" + count)).css("display", "none")
279                     })
280                     $('#tab_close' + count).click(
281                     function(event) {
282
283                             if (document.getElementById("timeout").disabled) {
284                                     return false;
285                             }
286                             $(this).parent().remove();
287                             for (var i = 1; i <= greatestIdNum(); i++) {
288                                     if ($("#formId" + i).length > 0) {
289                                             if (i !== count) {
290                                                     if ($("#formId" + i + " #parentPolicy").val() === $("#formId" + count + " #_id").val()
291                                                     .toString())
292                                                             $("#formId" + i + " #parentPolicy").val("")
293                                                     $(
294                                                     "#formId" + i + " #parentPolicy option[value='"
295                                                     + $("#formId" + count + " #_id").val().toString() + "']").remove();
296                                             }
297                                     }
298                             }
299                             delete policy_ids["#formId" + count + " #_id"]
300                             $("#formId" + count).remove();
301                     })
302             }
303             function greatestIdNum() {
304
305                     var greatest = 0;
306                     var s = $(".formId");
307                     for (var i = 0; i < s.length; i++) {
308                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
309                                     greatest = parseInt($(s[i]).attr("id").substring(6))
310                             }
311                     }
312                     return greatest;
313             }
314             // Generate random id for each policy
315             // Also made sure ids couldnt be repeated
316             function makeid(num) {
317
318                     var text = "";
319                     var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
320                     if (num == null)
321                             num = 7;
322                     for (var i = 0; i < 7; i++)
323                             text += possible.charAt(Math.floor(Math.random() * possible.length));
324                     var hasValue = false;
325                     for (k in policy_ids) {
326                             if (text === policy_ids[k])
327                                     hasValue = true
328                     }
329                     if (hasValue)
330                             return makeid(num);
331                     else
332                             return text
333             }
334             // var ParentPolicy = function(id, name) {
335             //
336             // this.id = id
337             // this.name = name
338             // }
339             function saveLastPolicyLocally(lastPolicyId) {
340
341                     console.log("last policy id is:" + lastPolicyId);
342                     var polForm = []
343                     var properties = $(".saveProps").not("#formSpan .saveProps");
344                     var timeoutForm = $("#Timeoutform").serializeArray();
345                     for (var i = 0; i < timeoutForm.length; i++) {
346                             polForm.push(timeoutForm[i]);
347                     }
348                     var d = {}
349                     d["policyConfigurations"] = [];
350                     for (var i = 0; i < properties.length; i++) {
351                             var ser = $(properties[i]).serializeArray();
352                             var s = noRepeats(ser)
353                             d["policyConfigurations"].push(s);
354                     }
355                     polForm.push(d);
356                     for ( var x in allPolicies) {
357                             if (x !== lastPolicyId) {
358                                     delete allPolicies[x];
359                                     console.log("remove old policy" + x);
360                             }
361                     }
362                     allPolicies[lastPolicyId] = polForm;
363             }
364             function startNextItem() {
365
366                     console.log("start next Item, policyname is:" + $("#pname").val());
367                     // save last item before transitioning
368                     var lastItem = $("#policyTable .highlight");
369                     console.log("start next Item, lastitem is:" + lastItem);
370                     if (lastItem.length > 0) {
371                             console.log("start next Item length > 0");
372                             saveLastPolicyLocally($("#pname").val());
373                             // lastItem.attr("id", $("#pname").val());
374                             lastItem.find("td").html($("#pname").val());
375                     }
376             }
377             function add_new_policy(issueNewNames) {
378
379                     console.log("add new policy");
380                     // remove old gui forms
381                     for (var i = 1; i < ($(".formId").length + 1); i++) {
382                             $("#go_properties_tab" + i).parent().remove();
383                     }
384                     $(".formId").remove();
385                     $("#pname").val("New_Policy");
386                     $("#timeout").val(getOperationalPolicyProperty().timeout);
387                     $("#add_one_more").click();
388             }
389             $scope.changeTargetResourceIdOther = function() {
390
391                     var formItemActive = searchActiveFormId();
392                     if (formItemActive === undefined)
393                             return;
394                     if ($("#" + formItemActive.id + " #targetResourceId").val() === "Other:") {
395                             $("#" + formItemActive.id + " #targetResourceIdOther").show();
396                     } else {
397                             $("#" + formItemActive.id + " #targetResourceIdOther").hide();
398                             $("#" + formItemActive.id + " #targetResourceIdOther").val("");
399                     }
400             }
401             $scope.changeGuardPolicyType = function() {
402
403                     var formItemActive = searchActiveFormId();
404                     if (formItemActive === undefined)
405                             return;
406                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
407                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
408                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
409                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
410                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
411                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
412                     }
413             }
414             $scope.init = function() {
415
416                     $(function() {
417
418                             $("#add_one_more").click(function(event) {
419
420                                     console.log("add one more");
421                                     event.preventDefault();
422                                     var num = add_one_more();
423                                     setMultiSelect();
424                             });
425                             var obj = getOperationalPolicyProperty();
426                             var loadPolicy;
427                             console.log("lastElementSelected :" + lastElementSelected);
428                             if (!($.isEmptyObject(obj))) {
429                                     allPolicies = jQuery.extend({}, obj);
430                                     for ( var x in allPolicies) {
431                                             $("#policyTable").prepend("<tr><td>" + x + "</td></tr>");
432                                             if (allPolicies[x][1]['value']) {
433                                                     allPolIds.push(parseInt(allPolicies[x][1]['value']));
434                                             }
435                                             console.log("policies found :" + x);
436                                             loadPolicy = x;
437                                     }
438                             }
439                             if (loadPolicy !== undefined && loadPolicy !== null) {
440                                     // load properties
441                                     console.log("load properties");
442                                     disperseConfig(allPolicies, loadPolicy);
443                             } else {
444                                     console.log("create new policy");
445                                     add_new_policy();
446                             }
447                             $("#savePropsBtn").click(
448                             function(event) {
449
450                                     console.log("save properties triggered");
451                                     if ($("#targetResourceIdOther").is(":visible")) {
452                                             $('#targetResourceId').append(
453                                             $('<option></option>').val($("#targetResourceIdOther").val()).html(
454                                             $("#targetResourceIdOther").val()))
455                                             $("#targetResourceId").val($("#targetResourceIdOther").val());
456                                     }
457                                     $(".idError").hide();
458                                     console.log("save properties triggered2");
459                                     startNextItem();
460                                     console.log("get all policies");
461                                     var finalSaveList = {};
462                                     $("#policyTable td").each(function() {
463
464                                             console.log("enter policy table each loop");
465                                             var tableVal = $(this).text();
466                                             if (tableVal in allPolicies) {
467                                                     finalSaveList[tableVal] = allPolicies[tableVal];
468                                             }
469                                             console.log("save properties; add tableVal to policies: " + tableVal);
470                                     });
471                                     var scope = angular.element(document.getElementById('formSpan')).scope();
472                                     scope.submitForm(finalSaveList);
473                                     $("#close_button").click();
474                             });
475                             $('#policyTable').on('click', 'tr', function(event) {
476
477                                     console.log("click on policyTable");
478                                     $(".idError").hide();
479                                     if (!(readMOnly)) {
480                                             startNextItem();
481                                     }
482                                     $(this).addClass('highlight').siblings().removeClass('highlight');
483                                     disperseConfig(allPolicies, $(this).find("td").html());
484                             });
485                             $('#pname').on('keypress', function(e) {
486
487                                     /*
488                                          * var newVal = $(this).val() +
489                                          * String.fromCharCode(e.which); if ((newVal>99) ||
490                                          * (($(this).val().length>2) && e.keyCode != 46 && e.keyCode
491                                          * !=8)){ e.preventDefault(); }
492                                          */
493                                     if (e.keyCode == 32) {
494                                             $("#spaceError").show();
495                                             e.preventDefault();
496                                     }
497                             });
498                             console.log("start next Item on 796");
499                             startNextItem();
500                             if (("#policyTable .highlight").length > 0) {
501                                     $('#policyTable tr.highlight').removeClass('highlight');
502                             }
503                             $("#policyTable").prepend("<tr class='highlight'><td>New_Policy</td></tr>");
504                             $("#pid").val(0);
505                             initTargetResourceId();
506                             // load metrics dropdown
507                             if (elementMap["global"]) {
508                                     for (var i = 0; i < (elementMap["global"].length); i++) {
509                                             if ((elementMap["global"][i]["name"]) == "actionSet") {
510                                                     var asSel = elementMap["global"][i]["value"];
511                                                     if (asSel == "vnfRecipe" && vf_Services !== null && vf_Services !== undefined) {
512                                                             if (vf_Services["policy"][asSel]) {
513                                                                     $.each((vf_Services["policy"][asSel]), function(val, text) {
514
515                                                                             $('#recipe').append($('<option></option>').val(val).html(text));
516                                                                     });
517                                                             }
518                                                             break;
519                                                     }
520                                             }
521                                     }
522                             }
523                     });
524             }
525             $scope.init();
526             $scope.isNumberKey = function(event) {
527
528                     var charCode = (event.which) ? event.which : event.keyCode
529                     if (charCode > 31 && (charCode < 48 || charCode > 57)) {
530                             return false;
531                     }
532                     return true;
533             }
534 //          setTimeout(function() {
535 //
536 //                  console.log("setTimeout");
537 //                  setMultiSelect();
538 //          }, 100);
539             $scope.close = function() {
540
541                     console.log("close");
542                     $uibModalInstance.close("closed");
543             };
544             $scope.submitForm = function(obj) {
545
546                     var operationalPolicies = JSON.parse(JSON.stringify(getOperationalPolicies()));
547                     if (obj !== null) {
548                             operationalPolicies[0]["configurationsJson"] = obj;
549                     }
550                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
551
552                             updateOpPolicyProperties(operationalPolicies);
553                     }, function(data) {
554
555                     });
556             };
557     } ]);