Merge "Rework the UI Menu"
[clamp.git] / src / main / resources / META-INF / resources / designer / scripts / CldsModelService.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 .service(
25 'cldsModelService',
26 [
27     'alertService',
28     '$http',
29     '$q',
30     '$rootScope',
31     function(alertService, $http, $q, $rootScope) {
32
33             function checkIfElementType(name) {
34
35         //This will open the methods located in the app.js
36                           if (undefined == name) {
37                                   return;
38                           }else if (name.toLowerCase().indexOf("policy") >= 0){
39                                           PolicyWindow();
40                           } else {
41                                   $rootScope.selectedBoxName = name.toLowerCase();
42                                   ToscaModelWindow();
43                           }
44             }
45             function handleQueryToBackend(def, svcAction, svcUrl, svcPayload) {
46
47                     $http.put(svcUrl, svcPayload).success(
48                     function(data) {
49
50                             def.resolve(data);
51                             if (typeof data.statusCodeValue === 'undefined'
52                             || data.statusCodeValue === 200) {
53                                     alertService.alertMessage(
54                                     "Action Successful: " + svcAction, 1)
55                             } else {
56                                     if (typeof data.body !== 'undefined') {
57                                             alertService.alertMessage("Action Failure: "
58                                             + svcAction + ", " + data.body.errorMessageForUi, 2);
59                                     } else {
60                                             alertService.alertMessage("Action Failure: "
61                                             + svcAction, 2);
62                                     }
63                                     def.reject(svcAction + " not successful");
64                             }
65                     }).error(
66                     function(data) {
67
68                             def.resolve(data);
69                             if (typeof data.body !== 'undefined') {
70                                     alertService.alertMessage("Action Failure: " + svcAction
71                                     + ", " + data.body.errorMessageForUi, 2);
72                             } else {
73                                     alertService
74                                     .alertMessage("Action Failure: " + svcAction, 2);
75                             }
76                             def.reject(svcAction + " not successful");
77                     });
78             }
79             this.toggleDeploy = function(uiAction, modelName, controlNamePrefixIn,
80                                          bpmnTextIn, propTextIn, svgXmlIn,
81                                          templateName, typeID, controlNameUuid,
82                                          modelEventService, deploymentId) {
83
84                     var def = $q.defer();
85                     var sets = [];
86                     var action = uiAction.toLowerCase();
87                     var deployUrl = "/restservices/clds/v1/clds/" + action + "/"
88                     + modelName;
89                     var requestData = {
90                         name : modelName,
91                         controlNamePrefix : controlNamePrefixIn,
92                         bpmnText : bpmnTextIn,
93                         propText : propTextIn,
94                         imageText : svgXmlIn,
95                         templateName : templateName,
96                         typeId : typeID,
97                         controlNameUuid : controlNameUuid,
98                         event : modelEventService,
99                         deploymentId : deploymentId
100                     };
101                     handleQueryToBackend(def, action, deployUrl, requestData);
102                     return def.promise;
103             };
104             this.getModel = function(modelName) {
105                     var def = $q.defer();
106                     var sets = [];
107                     var svcUrl = "/restservices/clds/v1/clds/model/" + modelName;
108                     $http.get(svcUrl).success(function(data) {
109                         var clModel = '{"name": "ClosedLoopTest","lastComputedState":"DESIGN","svgRepresentation": "representation","globalPropertiesJson": [{"name":"service","value":["4cc5b45a-1f63-4194-8100-cd8e14248c92"]},{"name":"vf","value":["07e266fc-49ab-4cd7-8378-ca4676f1b9ec"]},{"name":"actionSet","value":["vnfRecipe"]},{"name":"location","value":["DC1"]},{"name":"deployParameters","value":{"location_id":"","service_id":"","policy_id":"AUTO_GENERATED_POLICY_ID_AT_SUBMIT"}}], "blueprint": "yaml","lastComputedState": "DESIGN","operationalPolicies": [ {"name": "OpPolicyTest", "configurationsJson": { "policy1": [{"name": "pname","value": "policy1"},{"name": "pid","value": "0"},{"name": "timeout","value": "345"},{"policyConfigurations": [[{"name": "recipe","value": ["restart"]},{"name": "maxRetries","value": ["3"]},{"name": "retryTimeLimit","value": ["180"]},{"name": "_id","value": ["6TtHGPq"]},{"name": "parentPolicy","value": [""]},{"name": "actor","value": ["APPC"]},{"name": "recipeInput","value": [""]},{"name": "recipeLevel","value": ["VM"]},{"name": "targetResourceId","value": ["07e266fc-49ab-4cd7-8378-ca4676f1b9ec"]},{"name": "targetResourceIdOther","value": [""]},{"name": "enableGuardPolicy","value": ["on"]},{"name": "guardPolicyType","value": ["GUARD_YAML"]},{"name": "guardTargets","value": [".*"]},{"name": "minGuard","value": ["1"]},{"name": "maxGuard","value": ["1"]},{"name": "limitGuard","value": ["1"]},{"name": "timeUnitsGuard","value": ["minute"]},{"name": "timeWindowGuard","value": ["10"]},{"name": "guardActiveStart","value": ["00:00:01-05:00"]},{"name": "guardActiveEnd","value": ["00:00:00-05:00"]}]]}]} }],"microServicePolicies": [{"name": "tca","properties": "", "shared": true,"policyTosca": "tosca","jsonRepresentation": {"schema":{"title":"DCAE TCA Config","type":"object","required":["name","eventName"],"properties":{"name":{"propertyOrder":101,"title":"Name","type":"string","default":"New_Set"},"eventName":{"propertyOrder":102,"title":"EventName","type":"string","enum":["event1","event2"]},"clSchemaType":{"propertyOrder":103,"title":"Control Loop Schema Type","type":"string","enum":["","type1","type2"]},"threshold":{"propertyOrder":104,"title":"Threshold","format":"tabs","type":"array","items":{"type":"object","title":"Threshold","required":["metric","operator"],"properties":{"metric":{"propertyOrder":1001,"title":"Metric","type":"string","enum":["metric1","metric2"]},"operator":{"propertyOrder":1003,"default":">","title":"Operator","type":"string","enum":[">","<","=","<=",">="]}, "clEventStatus":{"propertyOrder":1004,"title":"Closed Loop Event Status","type":"string","enum":["","ONSET","ABATED"]}}}}}}}}],"loopLogs": [{ } ] }';
110                         cl_props = JSON.parse(clModel);
111                             def.resolve(data);
112                     }).error(function(data) {
113
114                             def.reject("Open Model not successful");
115                     });
116                     return def.promise;
117             };
118             this.getSavedModel = function() {
119
120                     var def = $q.defer();
121                     var sets = [];
122                     var svcUrl = "/restservices/clds/v1/clds/model-names";
123                     $http.get(svcUrl).success(function(data) {
124
125                             def.resolve(data);
126                     }).error(function(data) {
127
128                             def.reject("Open Model not successful");
129                     });
130                     return def.promise;
131             };
132             this.setModel = function(modelName, controlNamePrefixIn, bpmnTextIn,
133                                      propTextIn) {
134
135                     var def = $q.defer();
136                     var sets = [];
137                     var svcUrl = "/restservices/clds/v1/clds/model/" + modelName;
138                     var svcRequest = {
139                         name : modelName,
140                         controlNamePrefix : controlNamePrefixIn,
141                         bpmnText : bpmnTextIn,
142                         propText : propTextIn
143                     };
144                     $http.put(svcUrl, svcRequest).success(function(data) {
145
146                             def.resolve(data);
147                     }).error(function(data) {
148
149                             def.reject("Save Model not successful");
150                     });
151                     return def.promise;
152             };
153             this.processAction = function(uiAction, modelName, controlNamePrefixIn,
154                                           bpmnTextIn, propTextIn, svgXmlIn,
155                                           templateName, typeID, deploymentId) {
156
157                     var def = $q.defer();
158                     var sets = [];
159                     // console.log(svgXmlIn);
160                     var svcUrl = "/restservices/clds/v1/clds/";
161                     var svcAction = uiAction.toLowerCase();
162                     if (svcAction == "save" || svcAction == "refresh") {
163                             svcUrl = svcUrl + "model/" + modelName;
164                     } else if (svcAction == "test") {
165                             svcUrl = svcUrl + "action/submit/" + modelName + "?test=true";
166                     } else {
167                             svcUrl = svcUrl + "action/" + svcAction + "/" + modelName;
168                     }
169                     var svcRequest = {
170                         name : modelName,
171                         controlNamePrefix : controlNamePrefixIn,
172                         bpmnText : bpmnTextIn,
173                         propText : propTextIn,
174                         imageText : svgXmlIn,
175                         templateName : templateName,
176                         typeId : typeID,
177                         deploymentId : deploymentId
178                     };
179                     handleQueryToBackend(def, svcAction, svcUrl, svcRequest);
180                     return def.promise;
181             };
182             this.manageAction = function(modelName, typeId, typeName) {
183
184                     var def = $q.defer();
185                     var sets = [];
186                     var config = {
187                         url : "/restservices/clds/v1/clds/getDispatcherInfo",
188                         method : "GET",
189                         params : {
190                             model : modelName,
191                             typeId : typeId,
192                             typeName : typeName
193                         }
194                     };
195                     $http(config).success(function(data) {
196
197                             def.resolve(data);
198                     }).error(function(data) {
199
200                             def.reject("manage action not successful");
201                     });
202                     return def.promise;
203             };
204             this.processActionResponse = function(modelName, pars) {
205
206                     // populate control name (prefix and uuid here)
207                     var headerText = "Closed Loop Modeler - " + modelName;
208                     setStatus();
209                     disableBPMNAddSVG(pars);
210                     enableDisableMenuOptions();
211             };
212             this.processRefresh = function(pars) {
213
214                     var newPars = pars;
215                     if (typeof pars.body !== 'undefined') {
216                             newPars = pars.body;
217                     }
218                     typeID = newPars.typeId;
219                     deploymentId = newPars.deploymentId;
220                     setStatus(newPars);
221                     enableDisableMenuOptions();
222             }
223             function setStatus() {
224
225                     var status = getStatus();
226                     // apply color to status
227                     var statusColor = 'white';
228                     if (status.trim() === "DESIGN") {
229                             statusColor = 'gray'
230                     } else if (status.trim() === "DISTRIBUTED") {
231                             statusColor = 'blue'
232                     } else if (status.trim() === "ACTIVE") {
233                             statusColor = 'green'
234                     } else if (status.trim() === "STOPPED") {
235                             statusColor = 'red'
236                     } else if (status.trim() === "DELETING") {
237                             statusColor = 'pink'
238                     } else if (status.trim() === "ERROR") {
239                             statusColor = 'orange'
240                     } else if (status.trim() === "UNKNOWN") {
241                             statusColor = 'blue'
242                     } else {
243                             statusColor = null;
244                     }
245                     var statusMsg = '<span style="background-color:'
246                     + statusColor
247                     + ';-moz-border-radius: 50px;  -webkit-border-radius: 50px;  border-radius: 50px;">&nbsp;&nbsp;&nbsp;'
248                     + status + '&nbsp;&nbsp;&nbsp;</span>';
249                     // display status
250                     if ($("#status_clds").length >= 1)
251                             $("#status_clds").remove();
252                     $("#activity_modeler")
253                     .append(
254                     '<span id="status_clds" style="position: absolute;  left: 61%;top: 151px; font-size:20px;">Status: '
255                     + statusMsg + '</span>');
256             }
257             function disableBPMNAddSVG(pars) {
258
259                     var svg = pars.imageText.substring(pars.imageText.indexOf("<svg"))
260                     if ($("#svgContainer").length > 0)
261                             $("#svgContainer").remove();
262                     $("#js-canvas").append(
263                     "<span id=\"svgContainer\">" + svg + "</span>");
264                     /* added code for height width viewBox */
265                     $("#svgContainer svg").removeAttr("height");
266                     $("#svgContainer svg").removeAttr('viewBox');
267                     $("#svgContainer svg").removeAttr('width');
268                     $("#svgContainer svg").attr('width', '100%');
269                     $("#svgContainer svg").attr('height', '100%');
270                     $("#svgContainer").click(
271                     function(event) {
272
273                             // console.log($(event.target).parent().html())
274                             // console.log($($(event.target).parent()).attr("data-element-id"))
275                             var name = $($(event.target).parent()).attr("data-element-id")
276                             lastElementSelected = $($(event.target).parent()).attr(
277                             "data-element-id")
278                             checkIfElementType(name)
279                     });
280             }
281             enableDisableMenuOptions = function() {
282                 //var status = getStatus();
283                 var status = "DESIGN";
284                     // dropdown options - always true
285                 enableDefaultMenu();
286                     // enable/disable menu options based on permittedActionCd
287                     // list
288                 enableActionMenu(status);
289             }
290     } ]);