Upgrade sonar plugin
[vid.git] / vid-app-common / src / main / webapp / app / vid / scripts / modals / new-scheduler / new-scheduler.controller.js
1 (function () {
2     'use strict';
3
4     appDS2.controller("newSchedulerController", ["$scope", "$uibModal", "$uibModalInstance", "AaiService", "SchedulerService", "_",
5         "$log", "changeManagement", "$timeout", "$interval", "$filter", "VIDCONFIGURATION", "changeManagementService", newSchedulerController]);
6
7     function newSchedulerController($scope, $uibModal, $uibModalInstance, AaiService, SchedulerService, _, $log, changeManagement, $timeout, $interval, $filter, VIDCONFIGURATION, changeManagementService) {
8         var vm = this;
9         var pollpromise;
10
11         var init = function () {
12             vm.scheduler = {};
13             vm.schedulingInfo = {};
14             var callbackData = extractChangeManagementCallbackDataStr(changeManagement);
15             vm.vnfObject = changeManagement;
16             vm.schedulerObj = {
17                 domain: 'ChangeManagement',
18                 scheduleId: '',
19                 scheduleName: 'VnfUpgrade/DWF',
20                 userId: '',
21                 domainData: [{
22                     'WorkflowName': vm.scheduler.policy,
23                     'CallbackUrl': 'http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid',
24                     'CallbackData': callbackData
25                 }],
26
27                 schedulingInfo: {
28                     normalDurationInSeconds: '',
29                     additionalDurationInSeconds: '',
30                     concurrencyLimit: '',
31                     policyId: '',
32                     vnfDetails: [
33                         {
34                             groupId: "",
35                             node: [],
36                             changeWindow: [{
37                                 startTime: '',
38                                 endTime: ''
39                             }]
40
41                         }
42                     ]
43                 },
44
45             }
46             vm.schedulerObj1 = {
47                 "domain": "ChangeManagement",
48                 "scheduleName": "VnfUpgrade/DWF",
49                 "userId": "su7376",
50                 "domainData": [
51                     {
52                         "WorkflowName": "HEAT Stack Software Update for vNFs",
53                         "CallbackUrl": "http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid",
54                         "CallbackData": "testing"
55                     }
56                 ],
57                 "schedulingInfo": {
58                     "normalDurationInSeconds": 60,
59                     "additionalDurationInSeconds": 60,
60                     "concurrencyLimit": 60,
61                     "policyId": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml",
62                     "vnfDetails": [
63                         {
64                             "groupId": "group1",
65                             "node": ["satmo415vbc", "satmo455vbc"],
66                             "changeWindow": [
67                                 {
68                                     "startTime": "2017-08-08T16:37:30.521Z",
69                                     "endTime": "2017-08-08T16:37:30.521Z"
70                                 }
71                             ]
72                         }
73                     ]
74                 }
75             };
76
77
78             vm.format = 'yyyy/MM/dd';
79             vm.todate = new Date();
80             vm.checkboxSelection = 'false';
81             vm.fromDate = '';
82             vm.toDate = '';
83             vm.timeSlots = [];
84
85             vm.changeManagement = {};
86
87             vm.subscribers = [];
88
89             AaiService.getSubscribers(function (response) {
90                 vm.subscribers = response;
91             });
92
93             vm.serviceTypes = [];
94             AaiService.getServices(function (response) {
95                 vm.serviceTypes = response.data.service;
96             });
97
98             changeManagementService.getWorkflows()
99                 .then(function (response) {
100                     vm.workflows = response.data;
101                 })
102                 .catch(function (error) {
103                     $log.error(error);
104                 });
105
106             //TODO: Get the VNF names from backend dynamically
107             vm.vnfNames = [];
108
109             //TODO: Get the VNF types from backend dynamically
110             vm.vnfTypes = [];
111
112             AaiService.getLoggedInUserID(function (response) {
113                 vm.userID = response.data;
114             });
115             vm.policys = [];
116
117             var policyName = JSON.stringify({
118                 policyName: "SNIRO_1710.*",
119                 configAttributes: {
120                     service: "PlacementOptimizationPolicy"
121                 }
122             });
123             SchedulerService.getPolicyInfo(policyName, function (response) {
124                 vm.policys = response.data.entity;
125             });
126         };
127
128         vm.radioSelections = function (test) {
129             if (vm.checkboxSelection == "true") {
130                 vm.fromDate = '';
131                 vm.toDate = ''
132             }
133         }
134         vm.close = function () {
135             $uibModalInstance.close();
136         };
137
138
139         function convertToSecs(number) {
140             var totalSecs;
141             if (vm.selectedOption === 'hours') {
142                 totalSecs = number * 3600;
143
144             }
145             else if (vm.selectedOption === 'minutes') {
146                 totalSecs = number * 60;
147             } else {
148                 totalSecs = number;
149             }
150             return totalSecs;
151         }
152
153         vm.submit = function () {
154             vm.schedulingInfo = {
155                 scheduleId: vm.schedulerID,
156                 approvalDateTime: '2017-08-08T16:37:30.521Z',
157                 approvalUserId: "sy6266",
158                 approvalStatus: 'Accepted',
159                 approvalType: 'Tier 2'
160             };
161
162             var approvalObj = JSON.stringify(vm.schedulingInfo);
163             SchedulerService.getSubmitForapprovedTimeslots(approvalObj, function (response) {
164                 if (response.status == 200) {
165                     openConfirmationModal("Successfully Sent for Approval");
166                 }
167
168             });
169         };
170
171         vm.reject = function () {
172             vm.schedulingInfo = {
173                 scheduleId: vm.schedulerID,
174                 approvalDateTime: '2017-08-08T16:37:30.521Z',
175                 approvalUserId: "sy6266",
176                 approvalStatus: 'Rejected',
177                 approvalType: 'Tier 2'
178             }
179
180             var approvalObj = JSON.stringify(vm.schedulingInfo)
181             SchedulerService.getSubmitForapprovedTimeslots(approvalObj, function (response) {
182                 if (response.status == 200) {
183                     openConfirmationModal("Successfully sent for Rejection");
184                 }
185
186             });
187         };
188
189         vm.schedule = function (myForm) {
190             $scope.$watch('fromDate', validateDates(myForm));
191             $scope.$watch('toDate', validateDates(myForm));
192             if (myForm.$valid) {
193                 sendSchedulerReq()
194             }
195         };
196
197
198         function sendSchedulerReq() {
199             var changeWindow = [{
200                 startTime: '',
201                 endTime: ''
202             }];
203             vm.timeSlots = [];
204             var fromDate = $filter('date')(new Date(vm.fromDate), "yyyy-MM-ddTHH:mmZ", "UTC");
205             var toDate = $filter('date')(new Date(vm.toDate), "yyyy-MM-ddTHH:mmZ", "UTC");
206
207             changeWindow[0].startTime = fromDate;
208             changeWindow[0].endTime = toDate;
209             vm.schedulerObj.userId = vm.userID;
210             vm.schedulerObj.domainData[0].WorkflowName = changeManagement.workflow;
211             vm.schedulerObj.schedulingInfo.normalDurationInSeconds = convertToSecs(vm.scheduler.duration);
212             vm.schedulerObj.schedulingInfo.additionalDurationInSeconds = convertToSecs(vm.scheduler.fallbackDuration);
213             vm.schedulerObj.schedulingInfo.concurrencyLimit = vm.scheduler.concurrency;
214             vm.schedulerObj.schedulingInfo.policyId = vm.scheduler.policy.policyName;
215             vm.schedulerObj.schedulingInfo['vnfDetails'][0].groupId = 'groupId';
216             vm.schedulerObj.schedulingInfo['vnfDetails'][0].node = getVnfData(changeManagement.vnfNames);
217
218             vm.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow = changeWindow;
219             if (vm.checkboxSelection == "true") {               //When Scheduled now we remove the changeWindow
220                 delete vm.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow;
221             }
222             vm.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow = changeWindow;
223             delete vm.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow;
224
225             var requestScheduler = JSON.stringify(vm.schedulerObj);
226             console.log(requestScheduler);
227             SchedulerService.getStatusSchedulerId(requestScheduler, function (response) {
228                 vm.schedulerID = response.data.uuid;
229                 vm.isSpinnerVisible = true;
230                 if (vm.schedulerID) {
231                     var scheduledID = JSON.stringify({scheduleId: vm.schedulerID});
232                     seviceCallToGetTimeSlots();
233                 }
234             });
235         }
236
237         function seviceCallToGetTimeSlots() {
238
239             SchedulerService.getTimeSotsForSchedulerId(vm.schedulerID, function (response) {
240                 if (vm.checkboxSelection == "false") {
241                     if (response.data.entity.schedule) {
242                         var scheduleColl = JSON.parse(response.data.entity.schedule);
243                         if (scheduleColl.length > 0) {
244                             vm.timeSlots = scheduleColl;
245                             vm.isSpinnerVisible = false;
246                             hasvaluereturnd = false;
247                             $scope.stopPoll();
248                             openConfirmationModal(response.data.entity.scheduleId + " Successfully Returned TimeSlots.");
249                         }
250
251                     }
252                     else {
253                         if (vm.timeSlots.length == 0 && hasthresholdreached == false) {
254                             var polltime = VIDCONFIGURATION.SCHEDULER_POLLING_INTERVAL_MSECS;
255                             pollpromise = poll(polltime, function () {
256                                 if (vm.timeSlots.length == 0) {
257                                     hasvaluereturnd = true;
258                                     seviceCallToGetTimeSlots()
259                                 }
260                                 else {
261                                     hasvaluereturnd = false;
262                                 }
263
264                             });
265
266                         } else {
267                             openConfirmationModal("Timeout error.")
268                         }
269                     }
270
271                 }
272                 else {
273                     if (response.data.entity) {
274                         vm.isSpinnerVisible = false;
275                         openConfirmationModal(response.data.entity.scheduleId + " Successfully Ready for Schedule.")
276                     }
277                 }
278
279             });
280
281         }
282
283         function openConfirmationModal(jobInfo) {
284             var modalInstance = $uibModal.open({
285                 templateUrl: 'app/vid/scripts/modals/alert-new-scheduler/alert-new-scheduler.html',
286                 controller: 'alertNewSchedulerController',
287                 controllerAs: 'vm',
288                 resolve: {
289                     jobInfo: function () {
290                         return jobInfo;
291                     }
292                 }
293             });
294         }
295
296         var hasvaluereturnd = true; // Flag to check
297         var hasthresholdreached = false;
298         var thresholdvalue = VIDCONFIGURATION.SCHEDULER_MAX_POLLS; // interval threshold value
299
300         function poll(interval, callback) {
301             return $interval(function () {
302                 if (hasvaluereturnd) {  //check flag before start new call
303                     callback(hasvaluereturnd);
304                 }
305
306                 thresholdvalue = thresholdvalue - 1;  //Decrease threshold value
307                 if (thresholdvalue == 0) {
308                     $scope.stopPoll(); // Stop $interval if it reaches to threshold
309                 }
310             }, interval)
311         }
312
313
314 // stop interval.
315         $scope.stopPoll = function () {
316             $interval.cancel(pollpromise);
317             thresholdvalue = 0;     //reset all flags.
318             hasvaluereturnd = false;
319             hasthresholdreached = true;
320             vm.isSpinnerVisible = false;
321         }
322
323         function getVnfData(arrColl) {
324             var vnfcolletion = [];
325
326             for (var i = 0; i < arrColl.length; i++) {
327                 vnfcolletion.push(arrColl[i].name);
328             }
329
330             return vnfcolletion
331         }
332
333         function validateDates(form) {
334             if (vm.checkboxSelection == "false") {
335
336                 if (form.startDate.$error.invalidDate || form.endDate.$error.invalidDate) {
337                     form.startDate.$setValidity("endBeforeStart", true);  //already invalid (per validDate directive)
338                 } else {
339                     //depending on whether the user used the date picker or typed it, this will be different (text or date type).
340                     //creating a new date object takes care of that.
341                     var endDate = new Date(vm.toDate);
342                     var startDate = new Date(vm.fromDate);
343                     form.startDate.$setValidity("endBeforeStart", endDate >= startDate);
344                 }
345             }
346         }
347
348
349         function extractChangeManagementCallbackDataStr(changeManagement) {
350             var result = {};
351
352             result.requestType = changeManagement.workflow;
353             result.requestDetails = [];
354
355             _.forEach(changeManagement.vnfNames, function (vnf) {
356
357                     var data = {
358                         vnfName: vnf.name,
359                         vnfInstanceId: vnf.id,
360                         modelInfo: {
361                             modelType: 'vnf',
362                             modelInvariantId: vnf.properties['model-invariant-id'],
363                             modelVersionId: vnf.modelVersionId,
364                             modelName: vnf.properties['vnf-name'],
365                             modelVersion: vnf.version,
366                             modelCustomizationName: vnf.properties['model-customization-name'],
367                             modelCustomizationId: vnf.properties['model-customization-id']
368                         },
369                         cloudConfiguration: {
370                             lcpCloudRegionId: vnf.availableVersions[0].cloudConfiguration.lcpCloudRegionId,
371                             tenantId: vnf.availableVersions[0].cloudConfiguration.tenantId
372                         },
373                         requestInfo: {
374                             source: vnf.availableVersions[0].requestInfo.source,
375                             suppressRollback: vnf.availableVersions[0].requestInfo.suppressRollback,
376                             requestorId: vnf.availableVersions[0].requestInfo.requestorId
377                         },
378                         relatedInstanceList: [],
379                         requestParameters: {
380                             usePreload: vnf.availableVersions[0].requestParameters.usePreload
381                         }
382                     };
383
384                     var serviceInstanceId = '';
385                     _.forEach(vnf['service-instance-node'], function (instanceNode) {
386                         if(instanceNode['node-type'] === 'service-instance'){
387                             serviceInstanceId = instanceNode.properties['service-instance-id'];
388                         }
389                     });
390
391
392                     _.forEach(vnf.availableVersions[0].relatedInstanceList, function (related) {
393
394                         var rel = related.relatedInstance;
395
396                         var relatedInstance = {
397                             instanceId: serviceInstanceId,
398                             modelInfo: {
399                                 modelType: rel.modelInfo.modelType,
400                                 modelInvariantId: rel.modelInfo.modelInvariantId,
401                                 modelVersionId: rel.modelInfo.modelVersionId,
402                                 modelName: rel.modelInfo.modelName,
403                                 modelVersion: rel.modelInfo.modelVersion,
404                                 modelCustomizationName: rel.modelInfo.modelCustomizationName,
405                                 modelCustomizationId: rel.modelInfo.modelCustomizationId
406                             }
407                         };
408
409                         if (rel.vnfInstanceId)
410                             relatedInstance.instanceId = rel.vnfInstanceId;
411
412                         data.relatedInstanceList.push({relatedInstance: relatedInstance});
413                     });
414
415
416                     result.requestDetails.push(data);
417                 }
418             );
419
420
421             // _.forEach(changeManagement.vnfNames, function (vnfName) {
422             //     if (vnfName && vnfName.version) {
423             //         if (vnfName.selectedFile) {
424             //             vnfName.version.requestParameters.userParams = vnfName.selectedFile;
425             //         }
426             //         result.requestDetails.push(vnfName.version)
427             //     }
428             // });
429
430             return JSON.stringify(result);
431         }
432
433         init();
434     };
435
436     appDS2.directive('validDate', function () {
437         return {
438             restrict: 'A',
439             require: 'ngModel',
440             link: function (scope, element, attrs, control) {
441                 control.$parsers.push(function (viewValue) {
442                     var newDate = model.$viewValue;
443                     control.$setValidity("invalidDate", true);
444                     if (typeof newDate === "object" || newDate == "") return newDate;  // pass through if we clicked date from popup
445                     if (!newDate.match(/^\d{1,2}\/\d{1,2}\/((\d{2})|(\d{4}))$/))
446                         control.$setValidity("invalidDate", false);
447                     return viewValue;
448                 });
449             }
450         };
451     })
452
453
454 })();
455