1 function SchedulerCtrl($rootScope , $scope,$state,widgetsCatalogService,$log,schedulerService,$filter,confirmBoxService,userProfileService,conf,$interval,$compile) {
2 /****define fields****/
4 /*Assign the data that's passed to scheduler UI*/
5 $scope.hasParentData = true;
6 $rootScope.schedulerID = '';
9 $scope.selectedPolicy={policyName:"",policyConfig:""};
10 $scope.scheduler = {};
11 $scope.schedulingInfo = {};
12 $scope.timeSlots = [];
13 $scope.changeManagement = {};
14 $rootScope.schedulerForm = {
15 checkboxSelection : 'false',
25 $scope.schedulerObj = {};
27 var tomorrow = new Date();
28 tomorrow.setDate(tomorrow.getDate() + 1);
29 $scope.minDate = tomorrow.toISOString().substring(0, 10);
33 $scope.durationEmpty=false;
34 $scope.concurrencyLimitEmpty = false;
35 $scope.fallBackDurationEmpty=false;
36 $scope.fromDateEmpty = false;
37 $scope.toDateEmpty=false;
39 /*interval values for getting time slots*/
40 var hasvaluereturnd = true;
41 var hasthresholdreached = false;
42 var thresholdvalue =10; // interval threshold value
51 /***** Functions for modal popup ******/
52 $scope.radioSelections=function (){
53 if( $rootScope.schedulerForm.checkboxSelection=="true"){
54 $rootScope.schedulerForm.fromDate='';
55 $rootScope.schedulerForm.toDate=''
59 /*Dropdown update: everytime values in dropdown chagnes, update the selected value*/
60 $scope.$watch('selectedPolicy.policyName', (newVal, oldVal) => {
61 for (var i = 0; i < $scope.policys.length; i++)
62 if ($scope.policys[i].policyName == newVal)
63 $scope.selectedPolicy = angular.copy($scope.policys[i]);;
66 $scope.$watch('selectedTimeUint.text', (newVal, oldVal) => {
67 for (var i = 0; i < $scope.timeUnit.length; i++)
68 if ($scope.timeUnit[i].text == newVal)
69 $scope.selectedTimeUint = angular.copy($scope.timeUnit[i]);;
73 * This function is to validate and check if the input is a valid date.
74 * There are two checkers in this function:
75 * Check 1: the input is a valid date object,return true, return false otherwise.
76 * Check 2: check if the input has the format of MM/DD/YYYY or M/D/YYYY and is a valid date value.
80 $scope.isDateValid = function(dateInput) {
81 /*Check 1: see if the input is able to convert into date object*/
82 if ( Object.prototype.toString.call(dateInput) === "[object Date]" )
84 /*Check 2: see if the input is the date format MM/DD/YYYY */
85 var isDateStrFormat = false;
87 /*check the format of MM/DD/YYYY or M/D/YYYY */
88 var startDateformat = dateInput.split('/');
89 if (startDateformat.length != 3)
91 var day = startDateformat[1];
92 var month = parseInt(startDateformat[0])-1;
93 var year = startDateformat[2];
96 /*check the input value and see if it's a valid date*/
97 var composedDate = new Date(year, month, day);
98 if(composedDate.getDate() == day && composedDate.getMonth() == month && composedDate.getFullYear() == year)
99 isDateStrFormat = true
101 isDateStrFormat =false;
105 return isDateStrFormat;
109 * This function is to check whether the input date is greater than current date or not.
113 $scope.isStartDateValidFromToday = function (date) {
114 if(!$scope.isDateValid(date))
116 var startDate = new Date(date);
117 var currentDate = new Date();
118 if(startDate<=currentDate)
124 * This function is to check whether the input to date is greater than input from date.
125 * @param fromDate , toDate
128 $scope.isToDateGreaterFromDate = function (fromDate,toDate) {
129 if(!$scope.isDateValid(fromDate) || !$scope.isDateValid(toDate))
131 var fromDateObj = new Date(fromDate);
132 var toDateObj = new Date(toDate);
133 if(toDateObj<=fromDateObj)
139 * This function is to get error message from the input json response object.
140 * @param response , method
143 $scope.parseErrorMsg = function(response, method){
147 var entityJson = JSON.parse(response.entity);
149 errorMsg = entityJson.requestError.text;
152 $log.error('SchedulerCtrl::' + method +' error: ' + err);
157 /***** Scheduler UI functions *****/
159 /* This function is to send scheduler task approval to scheduler microservice. */
160 $scope.submit = function () {
161 $rootScope.showSpinner =true;
163 var approvalDateTime = new Date($scope.timeSlots[0].startTime);
164 $scope.schedulingInfo={
165 scheduleId: $rootScope.schedulerID,
166 approvalDateTime:approvalDateTime.toISOString(),
167 approvalUserId:$scope.orgUserId,
168 approvalStatus:$scope.schedulerObjConst.approvalSubmitStatus,
169 approvalType: $scope.schedulerObjConst.approvalType
171 var approvalObj= JSON.stringify($scope.schedulingInfo)
172 schedulerService.postSubmitForApprovedTimeslots(approvalObj).then(response => {
173 if(response.status>=200 && response.status<=204){
174 confirmBoxService.showInformation("Successfully Sent for Approval").then(isConfirmed => {});
176 var errorMsg = $scope.parseErrorMsg(response, 'postSubmitForApprovedTimeslots');
177 confirmBoxService.showInformation("Failed to Send for Approval "+ errorMsg).then(isConfirmed => {
182 $log.error('SchedulerCtrl::postSubmitForApprovedTimeslots error: ' + err);
185 errorMsg = $scope.parseErrorMsg(err.data, 'postSubmitForApprovedTimeslots');
188 confirmBoxService.showInformation("There was a problem sending Schedule request. " + errorMsg).then(isConfirmed => {
192 $rootScope.showSpinner = false;
196 /* This function is to send scheduler task rejection to scheduler microservice. */
197 $scope.reject = function () {
198 $rootScope.showSpinner =true;
199 var approvalDateTime = new Date($scope.timeSlots[0].startTime);
200 $scope.schedulingInfo={
201 scheduleId: $rootScope.schedulerID,
202 approvalDateTime:approvalDateTime.toISOString(),
203 approvalUserId:$scope.orgUserId,
204 approvalStatus: $scope.schedulerObjConst.approvalRejectStatus,
205 approvalType: $scope.schedulerObjConst.approvalType
207 var approvalObj= JSON.stringify($scope.schedulingInfo)
208 schedulerService.postSubmitForApprovedTimeslots(approvalObj).then(response => {
209 if(response.status>=200 && response.status<=299){
210 confirmBoxService.showInformation("Successfully Sent for Reject").then(isConfirmed => {});
212 var errorMsg = $scope.parseErrorMsg(response, 'postSubmitForApprovedTimeslots');
213 confirmBoxService.showInformation("Failed to Send for Reject "+ errorMsg).then(isConfirmed => {});
216 $log.error('SchedulerCtrl::postSubmitForApprovedTimeslots error: ' + err);
219 errorMsg = $scope.parseErrorMsg(err.data, 'postSubmitForApprovedTimeslots');
222 confirmBoxService.showInformation("There was a problem rejecting Schedule request. " + errorMsg).then(isConfirmed => {
226 $rootScope.showSpinner = false;
230 /* This function is to send policy config and receive scheduler Id. */
231 function sendSchedulerReq(){
233 $scope.timeSlots.length=0;
234 $scope.schedulerObj.userId=$scope.orgUserId;
235 $scope.schedulerObj.domainData[0].WorkflowName=$scope.vnfObject.workflow;
236 $scope.schedulerObj.schedulingInfo.normalDurationInSeconds=convertToSecs($rootScope.schedulerForm.duration)
237 $scope.schedulerObj.schedulingInfo.additionalDurationInSeconds=convertToSecs($rootScope.schedulerForm.fallbackDuration)
238 $scope.schedulerObj.schedulingInfo.concurrencyLimit=parseInt($rootScope.schedulerForm.concurrencyLimit)
240 $scope.schedulerObj.schedulingInfo['vnfDetails'][0].groupId=$scope.schedulerObjConst.groupId;
241 $scope.schedulerObj.schedulingInfo['vnfDetails'][0].node=getVnfData($scope.vnfObject.vnfNames);
242 for(var i=0;i<$scope.policys.length;i++){
243 if($scope.policys[i].policyName == $scope.selectedPolicy.policyName){
245 var config = $scope.policys[i].config;
246 var configJson = JSON.parse(config);
247 $scope.selectedPolicy.policyConfig = configJson.policyName;
249 confirmBoxService.showInformation("There was a problem setting Policy config. Please try again later. " + err).then(isConfirmed => {
256 $scope.schedulerObj.schedulingInfo.policyId=$scope.selectedPolicy.policyConfig;
258 startTime:$filter('date')(new Date($rootScope.schedulerForm.fromDate), "yyyy-MM-ddTHH:mmZ", "UTC"),
259 endTime:$filter('date')(new Date($rootScope.schedulerForm.toDate), "yyyy-MM-ddTHH:mmZ", "UTC")
261 $scope.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow=changeWindow;
263 if($rootScope.schedulerForm.checkboxSelection=="true"){ //When Scheduled now we remove the changeWindow
264 delete $scope.schedulerObj.schedulingInfo['vnfDetails'][0].changeWindow;
266 var requestScheduler= JSON.stringify($scope.schedulerObj)
267 $rootScope.showSpinner = true;
268 schedulerService.getStatusSchedulerId(requestScheduler).then(response => {
271 if(response && response.entity!=null){
272 var errorMsg = $scope.parseErrorMsg(response, 'getStatusSchedulerId');
273 confirmBoxService.showInformation("There was a problem retrieving scheduler ID. Please try again later. " + errorMsg).then(isConfirmed => {
278 if(response && response.uuid){
279 $rootScope.schedulerID = response.uuid;
280 var scheduledID= JSON.stringify({scheduleId:$rootScope.schedulerID});
281 $scope.seviceCallToGetTimeSlots();
283 confirmBoxService.showInformation("There was a problem retrieving scheduler ID. Please try again later. " + response).then(isConfirmed => {
291 $rootScope.showSpinner = false;
292 $log.error('SchedulerCtrl::getStatusSchedulerId error: ' + err);
295 errorMsg = $scope.parseErrorMsg(err.data, 'getStatusSchedulerId');
298 confirmBoxService.showInformation("There was a problem retrieving scheduler ID. Please try again later." + errorMsg).then(isConfirmed => {
302 $rootScope.showSpinner = false;
306 /* This function is to get time slots from SNIRO */
307 $scope.seviceCallToGetTimeSlots = function(){
308 $rootScope.showTimeslotSpinner = true;
309 schedulerService.getTimeslotsForScheduler($rootScope.schedulerID).then(response => {
310 if($rootScope.schedulerForm.checkboxSelection=="false"){
311 if(response.entity && JSON.parse(response.entity).schedule){ //received the timeslots
312 var entityJson = JSON.parse(response.entity);
313 var scheduleColl=JSON.parse(entityJson.schedule);
314 if(scheduleColl.length>0){
315 $scope.timeSlots =scheduleColl;
316 hasvaluereturnd = false;
317 $rootScope.showTimeslotSpinner = false;
319 confirmBoxService.showInformation(entityJson.scheduleId +" Successfully Returned TimeSlots.").then(isConfirmed => {});
321 confirmBoxService.showInformation("No time slot available").then(isConfirmed => {
325 if($scope.timeSlots.length==0 && hasthresholdreached==false){
326 var polltime=$scope.schedulerObjConst.getTimeslotRate*1000;
327 pollpromise= poll(polltime, function () {
328 if($scope.timeSlots.length==0){
329 hasvaluereturnd = true;
330 $scope.seviceCallToGetTimeSlots()
332 hasvaluereturnd = false;
335 if($rootScope.showTimeslotSpinner === true){
336 $rootScope.showTimeslotSpinner = false;
337 hasthresholdreached = false;
338 confirmBoxService.showInformation("Failed to get time slot - Timeout error. Please try again later").then(isConfirmed => {
346 $rootScope.showTimeslotSpinner = false;
347 if($rootScope.schedulerForm.checkboxSelection=="false")
348 confirmBoxService.showInformation("Schedule ID :" + response.entity.scheduleId +" is ready to schedule.").then(isConfirmed => {});
350 var entityObj = JSON.parse(response.entity);
351 confirmBoxService.showInformation("ID :" + entityObj.scheduleId +" is successfully sent for Approval").then(isConfirmed => {
358 $log.error('SchedulerCtrl::seviceCallToGetTimeSlots error: ' + err);
359 $rootScope.showTimeslotSpinner = false;
360 confirmBoxService.showInformation("There was a problem retrieving time slows. Please try again later.").then(isConfirmed => {
367 $scope.closeModal = function(){
368 setTimeout(function(){ $rootScope.closeModal(); }, 500);
371 /* This function is to get policy list from policy microservice */
372 $scope.getPolicy = function(){
373 schedulerService.getPolicyInfo().then(res =>{
374 if(res==null || res=='' || res.status==null || !(res.status>=200 && res.status<=299)){
375 $log.error('SchedulerWidgetCtrl::getPolicyInfo caught error', res);
376 var errorMsg = $scope.parseErrorMsg(res, 'getPolicy');
377 confirmBoxService.showInformation('There was a problem retrieving ploicy. Please try again later. ' + errorMsg).then(isConfirmed => {
381 $scope.policys = res.entity;
385 $scope.removeXMLExtension = function(str){
386 return str.replace(".xml","");
389 $scope.schedule = function () {
390 if($scope.formValidation())
394 /*************utility functions**************/
396 function convertToSecs(number){
398 if($scope.selectedTimeUint.text === 'HOURS'){
399 totalSecs=number * 3600;
400 } else if($scope.selectedOption === 'MINUTES') {
401 totalSecs=number * 60;
408 function poll(interval, callback) {
409 return $interval(function () {
410 if (hasvaluereturnd) //check flag before start new call
411 callback(hasvaluereturnd);
412 thresholdvalue = thresholdvalue - 1; //Decrease threshold value
413 if (thresholdvalue == 0)
414 $scope.stopPoll(); // Stop $interval if it reaches to threshold
419 $scope.stopPoll = function () {
420 $interval.cancel(pollpromise);
421 thresholdvalue = 0; //reset all flags.
422 hasvaluereturnd = false;
423 hasthresholdreached=true;
424 $rootScope.showSpinner = false;
427 function getVnfData(arrColl){
429 for(var i=0;i<arrColl.length;i++)
430 vnfcolletion.push(arrColl[i].name);
434 function extractChangeManagementCallbackDataStr(changeManagement) {
436 result.requestType = changeManagement.workflow;
437 result.requestDetails = [];
438 _.forEach(changeManagement.vnfNames, function (vnfName) {
439 if (vnfName && vnfName.version) {
440 if (vnfName.selectedFile) {
441 vnfName.version.requestParameters.userParams = vnfName.selectedFile;
443 result.requestDetails.push(vnfName.version)
446 return JSON.stringify(result);
450 $scope.constructScheduleInfo = function(){
451 var callbackData = extractChangeManagementCallbackDataStr($scope.vnfObject);
452 $scope.schedulerObj = {
453 domain: $scope.schedulerObjConst.domain,
455 scheduleName: $scope.schedulerObjConst.scheduleName,
458 'WorkflowName': $scope.schedulerObjConst.WorkflowName,
459 'CallbackUrl': $scope.schedulerObjConst.CallbackUrl,
460 'CallbackData': callbackData
463 normalDurationInSeconds: '',
464 additionalDurationInSeconds: '',
465 concurrencyLimit: '',
481 $scope.formValidation = function(){
482 $scope.durationEmpty=false;
483 $scope.concurrencyLimitEmpty = false;
484 $scope.fallBackDurationEmpty=false;
485 $scope.fromDateGreater=false;
486 $scope.fromDateEmpty=false;
487 $scope.toDateEmpty=false;
488 if($rootScope.schedulerForm.duration=='')
489 $scope.durationEmpty=true;
490 if($rootScope.schedulerForm.fallbackDuration=='')
491 $scope.fallBackDurationEmpty=true;
492 if($rootScope.schedulerForm.concurrencyLimit=='')
493 $scope.concurrencyLimitEmpty = true;
494 if(!($rootScope.schedulerForm.fromDate instanceof Date))
495 $scope.fromDateEmpty=true;
496 if(!($rootScope.schedulerForm.toDate instanceof Date ))
497 $scope.toDateEmpty=true;
498 var fromDateObj = new Date($rootScope.schedulerForm.fromDate);
499 var toDateObj = new Date($rootScope.schedulerForm.toDate);
500 if(fromDateObj>toDateObj)
501 $scope.fromDateGreater = true;
502 if($scope.durationEmpty||$scope.fallBackDurationEmpty ||$scope.concurrencyLimitEmpty || (($scope.fromDateEmpty || $scope.toDateEmpty) && $rootScope.schedulerForm.checkboxSelection=='false' ) ||$scope.fromDateGreater)
504 if($rootScope.schedulerForm.checkboxSelection == false && (!isDateValid($rootScope.schedulerForm.toDate) || !isDateValid($rootScope.schedulerForm.fromDate)))
506 if($scope.selectedPolicy.policyName=='' || $scope.selectedPolicy.policyName=='Select Policy'){
507 confirmBoxService.showInformation("Policy is required").then(isConfirmed => {});
513 $scope.getScheduleConstant =function(){
514 schedulerService.getSchedulerConstants().then(res =>{
515 if(res==null || res=='' || res.status==null || res.status!="OK"){
516 $log.error('SchedulerWidgetCtrl::getSchedulerConstants caught error', res);
517 confirmBoxService.showInformation('There is a problem about the Scheduler UI. Please try again later.').then(isConfirmed => {
521 var response = res.response;
522 $scope.schedulerObjConst= {
523 domain: response.domainName,
524 scheduleName : response.scheduleName,
525 WorkflowName : response.workflowName,
526 CallbackUrl : response.callbackUrl,
527 approvalType : response.approvalType,
528 approvalSubmitStatus : response.approvalSubmitStatus,
529 approvalRejectStatus : response.approvalRejectStatus,
530 getTimeslotRate : response.intervalRate,
531 policyName : response.policyName,
532 groupId : response.groupId
534 $scope.constructScheduleInfo();
535 $scope.getPolicy() // get policy items for the dropdown in the scheduler UI
540 /*This function is to get the current logged in user id*/
541 $scope.getUserId = function(){
542 $rootScope.showSpinner = true;
543 userProfileService.getUserProfile()
545 $scope.orgUserId = profile.orgUserId;
547 $rootScope.showSpinner = false;
551 $scope.activateThis = function(ele){
552 $compile(ele.contents())($scope);
556 /** listening calls from parents **/
557 $scope.$on("submit", function(events,data){
561 $scope.$on("reject", function(events,data){
565 $scope.$on("schedule", function(events,data){
571 var init = function () {
572 $rootScope.showSpinner = false;
573 $scope.selectedTimeUint=$scope.timeUnit[0];
575 if($scope.$parent.parentData){
576 $scope.hasParentData = true;
577 $scope.message = $scope.$parent.parentData;
578 $scope.vnfObject = $scope.message.data;
579 $scope.schedulerObj = $scope.message.data;
581 $scope.getScheduleConstant(); //get Scheduler constants from properties file
583 //second approach to get data
584 var isModal = $( "#scheduler-body" ).hasClass( "b2b-modal-body" );
586 $scope.message = schedulerService.getWidgetData();
588 $scope.hasParentData = true;
589 $scope.vnfObject = $scope.message.data;
590 $scope.schedulerObj = $scope.message.data;
592 $scope.getScheduleConstant(); //get Scheduler constants from properties file
595 $scope.hasParentData = false;