f474cf41305e5a595fb01d5e646abb33cb25a37e
[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             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             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                     $("#formId" + count + " #clname").val($scope.clname);
96                     return count;
97             }
98             function addCustListen(count) {
99
100                     $('#go_properties_tab' + count).click(function(event) {
101
102                             $("#nav_Tabs li").removeClass("active");
103                             $(this).parent().addClass("active");
104                             $("#formId" + count).css("display", "")
105                             $(".formId").not($("#formId" + count)).css("display", "none")
106                     })
107                     $('#tab_close' + count).click(function(event) {
108
109                             $(this).parent().remove();
110                             $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + count + " #id").val()), 1);
111                             $("#formId" + count).remove();
112                     })
113             }
114             function greatestIdNum() {
115
116                     var greatest = 0;
117                     var s = $(".formId");
118                     for (var i = 0; i < s.length; i++) {
119                             if (parseInt($(s[i]).attr("id").substring(6)) > greatest) {
120                                     greatest = parseInt($(s[i]).attr("id").substring(6))
121                             }
122                     }
123                     return greatest;
124             }
125             function serializeElement(element) {
126
127                     var o = {};
128                     var a = element.serializeArray();
129                     $.each(a, function() {
130
131                             if (o[this.name]) {
132                                     if (!o[this.name].push) {
133                                             o[this.name] = [ o[this.name] ];
134                                     }
135                                     o[this.name].push(this.value || '');
136                             } else {
137                                     o[this.name] = this.value || '';
138                             }
139                     });
140                     return o;
141             }
142             function savePolicyLocally() {
143
144                     var polForm = {};
145                     var clPolForm = {};
146                     clPolForm = serializeElement($("#operationalPolicyHeaderForm"));
147                     allPolicies['guard_policies'] = {};
148                     var policiesArray = []
149                     $.each($(".formId"), function() {
150
151                             var policyProperties = serializeElement($("#" + this.id + " .policyProperties"));
152                             policyProperties["target"] = serializeElement($("#" + this.id + " .policyTarget"))
153                             policiesArray.push(policyProperties);
154                             // Now get the Guard
155                             if ($("#" + this.id + " #enableGuardPolicy").is(':checked')) {
156                                     var guardPolicyBody = serializeElement($("#" + this.id + " .guardProperties"));
157                                     var guardPolicyId = guardPolicyBody['id'];
158                                     delete guardPolicyBody['id'];
159                                     allPolicies['guard_policies'][guardPolicyId] = guardPolicyBody;
160                                     $scope.guard_ids.push(guardPolicyId);
161                             }
162                     });
163                     polForm['controlLoop'] = clPolForm;
164                     polForm['policies'] = policiesArray;
165                     allPolicies['operational_policy'] = polForm;
166             }
167             function add_new_policy() {
168
169                     console.log("add new policy");
170                     // remove old gui forms
171                     for (var i = 1; i < ($(".formId").length + 1); i++) {
172                             $("#go_properties_tab" + i).parent().remove();
173                     }
174                     $(".formId").remove();
175                     $("#add_one_more").click();
176             }
177             function configureComponents(allPolicies) {
178
179                     console.log("load properties to op policy");
180                     // Set the header
181                     $.each($('#operationalPolicyHeaderForm').find('.form-control'), function() {
182                             $(this).val(allPolicies['operational_policy']['controlLoop'][this.id]);
183                     });
184                     // Set the sub-policies
185                     $.each(allPolicies['operational_policy']['policies'], function(opPolicyElemIndex, opPolicyElemValue) {
186
187                             var formNum = add_one_more();
188                             $.each($('.policyProperties').find('.form-control'), function(opPolicyPropIndex, opPolicyPropValue) {
189
190                                     $("#formId" + formNum + " .policyProperties").find("#" + opPolicyPropValue.id).val(
191                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex][opPolicyPropValue.id]);
192                             });
193
194                             // Initial TargetResourceId options
195                             initTargetResourceIdOptions(allPolicies['operational_policy']['policies'][opPolicyElemIndex]['target']['type'], formNum);
196                             $.each($('.policyTarget').find('.form-control'), function(opPolicyTargetPropIndex, opPolicyTargetPropValue) {
197
198                                     $("#formId" + formNum + " .policyTarget").find("#" + opPolicyTargetPropValue.id).val(
199                                     allPolicies['operational_policy']['policies'][opPolicyElemIndex]['target'][opPolicyTargetPropValue.id]);
200                             });
201
202                             // update the current tab label
203                             $("#go_properties_tab" + formNum).text(
204                             allPolicies['operational_policy']['policies'][opPolicyElemIndex]['id']);
205                             // Check if there is a guard set for it
206                             $.each(allPolicies['guard_policies'], function(guardElemId, guardElemValue) {
207
208                                     if (guardElemValue.recipe === $($("#formId" + formNum + " #recipe")[0]).val()) {
209                                             // Found one, set all guard prop
210                                             $.each($('.guardProperties').find('.form-control'), function(guardPropElemIndex,
211                                                                                                          guardPropElemValue) {
212
213                                                     guardElemValue['id'] = guardElemId;
214                                                     $("#formId" + formNum + " .guardProperties").find("#" + guardPropElemValue.id).val(
215                                                     guardElemValue[guardPropElemValue.id]);
216                                             });
217                                             // And finally enable the flag
218                                             $("#formId" + formNum + " #enableGuardPolicy").prop("checked", true);
219                                     }
220                             });
221                     });
222             }
223             function initTargetResourceIdOptions (targetType, formNum) {
224                     var recipe = $("#formId" + formNum + "#recipe").val();
225                     $("#formId" + formNum + " #resourceId").empty();
226                     $("#formId" + formNum + " #resourceId").append($('<option></option>').val("").html("-- choose an option --"));
227
228                     var resourceVnf = getResourceDetailsVfProperty();
229                     if (targetType == "VNF" && (null !== resourceVnf || undefined !== resourceVnf)) {
230                             for ( var prop in resourceVnf) {
231                                     var name = resourceVnf[prop]["name"];
232                                     $("#formId" + formNum + " #resourceId").append($('<option></option>').val(name).html(name));
233                             }
234                     }
235                     var resourceVFModule = getResourceDetailsVfModuleProperty();
236                     if (targetType == "VFModule" && (null !== resourceVFModule || undefined !== resourceVFModule)) {
237                             if (recipe == 'VF Module Create' || recipe == 'VF Module Delete') {
238                                     for ( var prop in resourceVFModule) {
239                                             if (resourceVFModule[prop]["isBase"] == false) {
240                                                     $("#formId" + formNum + " #resourceId").append($('<option></option>').val(resourceVFModule[prop]["vfModuleModelName"]).html(resourceVFModule[prop]["vfModuleModelName"]));
241                                             }
242                                     }
243                             } else {
244                                     for ( var prop in resourceVFModule) {
245                                             $("#formId" + formNum + " #resourceId").append($('<option></option>').val(resourceVFModule[prop]["vfModuleModelName"]).html(resourceVFModule[prop]["vfModuleModelName"]));
246                                     }
247                             }
248                     }
249             }
250
251             function initTargetModelAttributes (formNum) {
252                     $("#formId" + formNum + " #modelName").val("");
253                     $("#formId" + formNum + " #modelInvariantId").val("");
254                     $("#formId" + formNum + " #modelVersionId").val("");
255                     $("#formId" + formNum + " #modelVersion").val("");
256                     $("#formId" + formNum + " #modelCustomizationId").val("");
257             }
258
259             $scope.initTargetResourceId = function(event) {
260                 var formNum = $(event.target).closest('.formId').attr('id').substring(6);
261                 initTargetModelAttributes(formNum);
262                     var type = $(event.target).val();
263                     initTargetResourceIdOptions(type, formNum);
264             }
265
266             $scope.changeTargetResourceId = function(event) {
267                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
268                     initTargetModelAttributes(formNum);
269
270                     var resourceVFModule = getResourceDetailsVfModuleProperty();
271                     var type = $("#formId" + formNum +" #type").val();
272                     var recipe = $("#formId" + formNum +" #recipe").val();
273                     if (type == "VFModule" && (null !== resourceVFModule || undefined !== resourceVFModule)
274                     && (recipe == 'VF Module Create' || recipe == 'VF Module Delete')) {
275                             for ( var prop in resourceVFModule) {
276                                     if (prop ==  $(event.target).val()) {
277                                             $("#formId" + formNum +" #modelName").val(resourceVFModule[prop]["vfModuleModelName"]);
278                                             $("#formId" + formNum +" #modelInvariantId").val(resourceVFModule[prop]["vfModuleModelInvariantUUID"]);
279                                             $("#formId" + formNum +" #modelVersionId").val(resourceVFModule[prop]["vfModuleModelUUID"]);
280                                             $("#formId" + formNum +" #modelVersion").val(resourceVFModule[prop]["vfModuleModelVersion"]);
281                                             $("#formId" + formNum +" #modelCustomizationId").val(resourceVFModule[prop]["vfModuleModelCustomizationUUID"]);
282                                             $("#formId" + formNum +" #metadata *").prop('disabled', false);
283                                     }
284                             }
285                     } else {
286                             $("#formId" + formNum +" #metadata *").prop('disabled', true);
287                     }
288             }
289             $scope.changeGuardPolicyType = function() {
290
291                     var formItemActive = searchActiveFormId();
292                     if (formItemActive === undefined)
293                             return;
294                     if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_MIN_MAX") {
295                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").show();
296                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").hide();
297                     } else if ($("#" + formItemActive.id + " #guardPolicyType").val() === "GUARD_YAML") {
298                             $("#" + formItemActive.id + " #minMaxGuardPolicyDiv").hide();
299                             $("#" + formItemActive.id + " #frequencyLimiterGuardPolicyDiv").show();
300                     }
301             }
302             $scope.initPolicySelect = function() {
303
304                     if (allPolicies['operational_policy'] === undefined || allPolicies['operational_policy'] === null) {
305                             allPolicies = getOperationalPolicyProperty();
306                     }
307                     // Provision all policies ID first
308                     if ($scope.policy_ids.length == 0 && allPolicies['operational_policy'] != undefined) {
309                             $.each(allPolicies['operational_policy']['policies'], function() {
310
311                                     $scope.policy_ids.push(this['id']);
312                             });
313                     }
314             }
315             $scope.init = function() {
316
317                     $(function() {
318
319                             $scope.clname = getLoopName();
320                             $("#add_one_more").click(function(event) {
321
322                                     console.log("add one more");
323                                     event.preventDefault();
324                                     $scope.policy_ids.push($("#formId" + add_one_more() + " #id").val());
325                             });
326                             if (allPolicies['operational_policy'] !== undefined && allPolicies['operational_policy'] !== null) {
327                                     // load properties
328                                     console.log("load properties");
329                                     configureComponents(allPolicies);
330                             } else {
331                                     console.log("create new policy");
332                                     add_new_policy();
333                             }
334                             $("#savePropsBtn").click(function(event) {
335
336                                     console.log("save properties triggered");
337                                     savePolicyLocally();
338                                     for (var i = 0; i <= $scope.guard_ids.length; i++) {
339                                             for (var j = i; j <= $scope.guard_ids.length; j++) {
340                                                     if (i != j && $scope.guard_ids[i] == $scope.guard_ids[j]) {
341                                                             // duplacated guard policy id exist
342                                                             alert("The guard policy ID should be unique.");
343                                                             return;
344                                                     }
345                                             }
346                                     }
347                                     angular.element(document.getElementById('formSpan')).scope().submitForm(allPolicies);
348                                     $("#close_button").click();
349                             });
350                     });
351             }
352             $scope.init();
353             $scope.updateGuardRecipe = function(event) {
354
355                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
356                     // Get the second recipe (guard one) and update it
357                     $($("#formId" + formNum + " #recipe")[1]).val($(event.target).val());
358             }
359             $scope.updateGuardActor = function(event) {
360
361                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
362                     // Get the second actor (guard one) and update it
363                     $($("#formId" + formNum + " #actor")[1]).val($(event.target).val());
364             }
365             // When we change the name of a policy
366             $scope.updateTabLabel = function(event) {
367
368                     // update policy id structure
369                     var formNum = $(event.target).closest('.formId').attr('id').substring(6);
370                     $scope.policy_ids.splice($scope.policy_ids.indexOf($("#formId" + formNum + " #id").val()), 1);
371                     $scope.policy_ids.push($(event.target).val());
372                     // Update the tab now
373                     $("#go_properties_tab" + formNum).text($(event.target).val());
374             }
375             $scope.close = function() {
376
377                     console.log("close");
378                     $uibModalInstance.close("closed");
379             };
380             $scope.submitForm = function(obj) {
381
382                     var operationalPolicies = getOperationalPolicies();
383                     if (obj !== null) {
384                             operationalPolicies[0]["configurationsJson"] = obj;
385                     }
386                     operationalPolicyService.saveOpPolicyProperties(operationalPolicies).then(function(pars) {
387
388                             updateOpPolicyProperties(operationalPolicies);
389                     }, function(data) {
390
391                     });
392             };
393     } ]);