Replace ecomp references
[portal.git] / ecomp-portal-FE-common / client / app / views / user-notifications-admin / user.notifications.modal.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 'use strict';
39
40 (function() {
41
42     class userNotificationsModalCtrl {
43         constructor($scope, $log, functionalMenuService, confirmBoxService, notificationService, $modal, ngDialog, $state, $filter, items) {
44             this.debug = false;
45             $scope.newNotifModel = {
46                 'isOnlineUsersOnly': null,
47                 'isForAllRolesOptions': null,
48                 'selectedPriority': null,
49                 'isActive': null,
50                 'startTime': '',
51                 'endTime': '',
52                 'msgHeader': null,
53                 'msgDescription': null,
54                 'roleIds': null,
55                 'anyTreeItemSelected': false,
56                 'roleObj': {
57                     notificationRoleIds: null
58                 }
59             };
60
61             $scope.notificationId = null;
62             $scope.selectedCat = null;
63             $scope.selectedEcompFunc = null;
64             this.YN_index_mapping = {
65                 "Y": 0,
66                 "N": 1
67             }
68
69             $scope.onlineAllUsersOptions = [{
70                     "index": 0,
71                     "value": "Y",
72                     "title": "Online Users Only"
73                 },
74                 {
75                     "index": 1,
76                     "value": "N",
77                     "title": "Online & Offline Users"
78                 }
79
80             ];
81
82             $scope.isForAllRolesOptions = [{
83                     "index": 0,
84                     "value": "Y",
85                     "title": "Yes"
86                 },
87                 {
88                     "index": 1,
89                     "value": "N",
90                     "title": "No"
91                 }
92             ];
93
94             $scope.priorityOptions = [{
95                     "index": 0,
96                     "value": 1,
97                     "title": "Normal"
98                 },
99                 {
100                     "index": 1,
101                     "value": 2,
102                     "title": "Important"
103                 }
104             ];
105
106             $scope.isActiveOptions = [{
107                     "index": 0,
108                     "value": "Y",
109                     "title": "Yes"
110                 },
111                 {
112                     "index": 1,
113                     "value": "N",
114                     "title": "No"
115                 }
116             ];
117             $scope.newNotifModel.isActive = $scope.isActiveOptions[0];
118             $scope.newNotifModel.selectPriority = $scope.priorityOptions[0];
119             $scope.newNotifModel.isOnlineUsersOnly = $scope.onlineAllUsersOptions[1];
120             $scope.newNotifModel.isForAllRoles = $scope.isForAllRolesOptions[0].value;
121             $scope.newNotifModel.isFunctionalMenu = "Y";
122
123             $scope.newNotifModel.selectedPriority = $scope.priorityOptions[0].value;
124             $scope.newNotifModel.msgHeader = '';
125             $scope.newNotifModel.msgDescription = '';
126             $scope.newNotifModel.treeTitle = "Functional Menu";
127             $scope.newNotifModel.notifObj = {
128                 isCategoriesFunctionalMenu: true
129             };
130
131             let init = () => {
132                 if (this.debug)
133                     $log.debug('userNotificationsModalCtrl::init');
134                 this.isSaving = false;
135                 var today = new Date();
136                 $scope.minDate = today.toISOString().substring(0, 10);
137                 var threeMonthsFromNow = new Date();
138                 threeMonthsFromNow.setMonth(threeMonthsFromNow.getMonth() + 3);
139                 $scope.maxDate = threeMonthsFromNow.toISOString().substring(0, 10);
140                 if (items && items.notif) {
141                     if (this.debug)
142                         $log.debug('userNotificationsModalCtrl:init:: Edit notification mode for', items.notif);
143                     $scope.isEditMode = true;
144                     $scope.editModeObj = {
145                         isEditMode: true
146                     };
147                     this.notif = _.clone(items.notif);
148                     $scope.modalPgTitle = 'View Notification'
149                     $scope.newNotifModel.isOnlineUsersOnly = $scope.onlineAllUsersOptions[this.YN_index_mapping[this.notif.isForOnlineUsers]];
150                     $scope.newNotifModel.isForAllRoles = $scope.isForAllRolesOptions[this.YN_index_mapping[this.notif.isForAllRoles]].value;
151                     $scope.newNotifModel.isActive = $scope.isActiveOptions[this.YN_index_mapping[this.notif.activeYn]];
152                     $scope.newNotifModel.selectedPriority = $scope.priorityOptions[this.notif.priority - 1].value;
153                     $scope.newNotifModel.startTime = new Date(this.notif.startTime);
154                     $scope.newNotifModel.endTime = new Date(this.notif.endTime);
155                     $scope.newNotifModel.msgHeader = this.notif.msgHeader;
156                     $scope.newNotifModel.msgDescription = this.notif.msgDescription;
157                     $scope.notificationId = this.notif.notificationId;
158                     $scope.newNotifModel.notificationRoleIds = this.notif.roleIds;
159                     $scope.roleObj = {
160                         notificationRoleIds: this.notif.roleIds
161                     };
162                 } else {
163                     if (this.debug)
164                         $log.debug('AppDetailsModalCtrl:init:: New app mode');
165                     $scope.isEditMode = false;
166                     $scope.editModeObj = {
167                         isEditMode: false
168                     };
169                     $scope.modalPgTitle = 'Add a New Notification'
170                     this.notif = _.clone($scope.newNotifModel);
171                     $scope.roleObj = {
172                         notificationRoleIds: null
173                     };
174                 }
175             };
176             this.conflictMessages = {};
177             this.scrollApi = {};
178             let handleConflictErrors = err => {
179                 if (!err.data) {
180                     return;
181                 }
182                 if (!err.data.length) { // support objects
183                     err.data = [err.data]
184                 }
185                 _.forEach(err.data, item => {
186                     _.forEach(item.fields, field => {
187                         // set conflict message
188                         this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
189                         // set field as invalid
190                         $scope.appForm[field.name].$setValidity('conflict', false);
191                         // set watch once to clear error after user correction
192                         watchOnce[field.name]();
193                     });
194                 });
195                 this.scrollApi.scrollTop();
196             };
197
198             let resetConflict = fieldName => {
199                 delete this.conflictMessages[fieldName];
200                 if ($scope.appForm[fieldName]) {
201                     $scope.appForm[fieldName].$setValidity('conflict', true);
202                 }
203             };
204             $scope.addUserNotificationValidation = function() {
205                 // // pre-processing
206                 if (!($scope.isEditMode)) {
207                     var validation = false;
208                     if ($scope.isStartDateValidFromToday($scope.newNotifModel.startTime)&&$scope.isStartDateValidFromToday($scope.newNotifModel.endTime)&&$scope.isDateValid($scope.newNotifModel.startTime) && $scope.isDateValid($scope.newNotifModel.endTime) && $scope.newNotifModel.msgHeader != '' && $scope.newNotifModel.msgDescription != '' && ($scope.newNotifModel.startTime < $scope.newNotifModel.endTime)) {
209                         validation = true;
210                         if ($scope.newNotifModel.isForAllRoles == 'N') {
211                             validation = $scope.checkTreeSelect();
212                         }
213                     } else {
214                         validation = false;
215                     }
216                     return !validation;
217                 }
218             }
219
220             /* format the value for viewing a notification */
221             $scope.formatStartDate = function() {
222                 if ($scope.newNotifModel.startTime) {
223                     $scope.newNotifModel.startTime = $filter('date')($scope.startTime, 'medium');
224                 }
225             }
226
227             /* format the value for viewing a notification */
228             $scope.formatEndDate = function() {
229                 if ($scope.newNotifModel.endTime) {
230                     $scope.newNotifModel.endTime = $filter('date')($scope.endTime, 'medium');
231                 }
232             }
233             
234             /*To validate the manual entry of date in MM/DD/YYYY Format*/
235
236             $scope.isDateValid = function(time) {
237                 if (time == undefined) {
238                     return false;
239                 }
240                 if (typeof time == 'object') {
241                     return true;
242                 }
243                 var startDateformat = time.split('/');
244                 if (startDateformat.length != 3) return false;
245                 var day = startDateformat[1];
246                 var month = startDateformat[0];
247                 month = parseInt(month) - 1;
248                 var year = startDateformat[2];
249                 if (year.length != 4) return false;
250                 var composedDate = new Date(year, month, day);
251                  return composedDate.getDate() == day &&
252                          composedDate.getMonth() == month &&
253                          composedDate.getFullYear() == year;
254             };
255             
256          /*The manual and drop down calendar should be consistent.
257          Start date must be greater than or equal to current date.The end dates are not allowed after the 3 months from current dates*/
258             
259             $scope.isStartDateValidFromToday = function (time) {
260                 if(time == undefined){
261                     return false;
262                 }
263                 if(typeof time == 'object'){
264                         return true;
265                 }
266                 var startDateformat     =time.split('/');
267                 if (startDateformat.length != 3) return true;
268                 var day = startDateformat[1];
269                 var month = startDateformat[0];
270                  month= parseInt(month)-1;
271                 var year = startDateformat[2];
272                 if(year.length!=4) return true;
273                 var composedDate = new Date(year, month, day);
274               /* As end dates are not allowed after the 3 months from current dates*/
275                 var x = 3; //or whatever offset
276                 var CurrentDate = new Date();
277                 /*If composed date is less than the current date,error message should display*/
278                 if(composedDate<CurrentDate)
279                         return false;
280                 CurrentDate.setMonth(CurrentDate.getMonth() + x);
281                 if(composedDate>CurrentDate)
282                         return false;
283                  return true;
284             };
285
286
287             $scope.addUserNotification = function() {
288                 $scope.notificationRoleIds = [];
289                 // pre-processing
290
291                 for (var fi = 0; fi < $scope.treedata.length; fi++) {
292                     var fLevel = $scope.treedata[fi];
293                     if (fLevel) {
294                         var fLevelChild = fLevel.child;
295                         if (fLevelChild) {
296                             for (var si = 0; si < fLevelChild.length; si++) {
297                                 var sLevel = fLevelChild[si];
298                                 if (sLevel) {
299                                     var sLevelChild = sLevel.child;
300                                     if (sLevelChild) {
301                                         for (var ti = 0; ti < sLevelChild.length; ti++) {
302                                             var tLevel = sLevelChild[ti];
303                                             if (tLevel.isSelected && tLevel.roleId) {
304                                                 $scope.newNotifModel.anyTreeItemSelected = true;
305                                                 for (var i in tLevel.roleId)
306                                                     $scope.notificationRoleIds.push(tLevel.roleId[i]);
307                                             }
308                                         }
309                                     }
310                                 }
311                                 if (sLevel.isSelected && sLevel.roleId) {
312                                     for (var i in sLevel.roleId)
313                                         $scope.notificationRoleIds.push(sLevel.roleId[i]);
314                                 }
315                             }
316                         }
317                     }
318                 }
319
320                 $scope.notificationRoleIds.sort();
321                 if (($scope.newNotifModel.isOnlineUsersOnly) && ($scope.newNotifModel.isForAllRoles) && ($scope.newNotifModel.selectedPriority) && ($scope.newNotifModel.isActive) &&
322                     ($scope.newNotifModel.startTime) && ($scope.newNotifModel.endTime) && ($scope.newNotifModel.msgHeader != '') && ($scope.newNotifModel.msgDescription != '')) {
323                     this.newUserNotification = {
324                         'notificationId': $scope.notificationId,
325                         'isForOnlineUsers': $scope.newNotifModel.isOnlineUsersOnly.value,
326                         'isForAllRoles': $scope.newNotifModel.isForAllRoles,
327                         'priority': $scope.newNotifModel.selectedPriority,
328                         'activeYn': $scope.newNotifModel.isActive.value,
329                         'startTime': $scope.newNotifModel.startTime,
330                         'endTime': $scope.newNotifModel.endTime,
331                         'msgHeader': $scope.newNotifModel.msgHeader,
332                         'msgDescription': $scope.newNotifModel.msgDescription,
333                         'roleIds': $scope.notificationRoleIds,
334                         'createdDate': new Date()
335                     };
336
337                     // POST ajax call here;
338                     if ($scope.isEditMode) {
339                         notificationService.updateAdminNotification(this.newUserNotification)
340                             .then(() => {
341                                 if (this.debug)
342                                     $log.debug('NotificationService:updateAdminNotification:: Admin notification update succeeded!');
343                                 $scope.closeThisDialog(true);
344                             }).catch(err => {
345                                 $log.error('notificationService.updateAdminNotfication failed: ' + JSON.stringify(err));
346                                 switch (err.status) {
347                                     case '409': // Conflict
348                                         // handleConflictErrors(err);
349                                         break;
350                                     case '500': // Internal Server Error
351                                         confirmBoxService.showInformation('There was a problem updating the notification. ' +
352                                             'Please try again later. Error: ' + err.status).then(isConfirmed => {});
353                                         break;
354                                     case '403': // Forbidden... possible
355                                         // webjunction error to
356                                         // try again
357                                         confirmBoxService.showInformation('There was a problem updating the notification. ' +
358                                             'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
359                                         break;
360                                     default:
361                                         confirmBoxService.showInformation('There was a problem updating the notification. ' +
362                                             'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
363                                 }
364                             }).finally(() => {
365                                 // for bug in IE 11
366                                 var objOffsetVersion = objAgent.indexOf("MSIE");
367                                 if (objOffsetVersion != -1) {
368                                     if (this.debug)
369                                         $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh');
370                                     $window.location.reload();
371                                 }
372                                 // for bug in IE 11
373                             });
374
375                     } else {
376                         notificationService.addAdminNotification(this.newUserNotification)
377                             .then((res) => {
378                                 if (this.debug)
379                                     $log.debug('notificationService:addAdminNotification:: Admin notification creation succeeded!,', res);
380                                 if (res.status == 'ERROR') {
381                                     confirmBoxService.showInformation('There was a problem adding the notification. ' +
382                                         ' Error: ' + res.response).then(isConfirmed => {});
383
384
385                                 } else {
386                                     // $scope.closeThisDialog(true);
387                                     $scope.$dismiss('cancel');
388                                 }
389
390                                 // emptyCookies();
391                             }).catch(err => {
392                                 switch (err.status) {
393                                     case '409': // Conflict
394                                         // handleConflictErrors(err);
395                                         break;
396                                     case '500': // Internal Server Error
397                                         confirmBoxService.showInformation('There was a problem adding the notification. ' +
398                                             'Please try again later. Error: ' + err.status).then(isConfirmed => {});
399                                         break;
400                                     default:
401                                         confirmBoxService.showInformation('There was a problem adding the notification. ' +
402                                             'Please try again. If the problem persists, then try again later. Error: ' +
403                                             err.status).then(isConfirmed => {});
404                                 }
405                                 $log.error('notificationService:addAdminNotification error:: ' + JSON.stringify(err));
406                             })
407                     }
408
409
410                 } else {
411                     $log.warn('please fill in all required fields');
412                     confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
413                 }
414             }
415             $scope.functionalMenuRes = {};
416             $scope.checkTreeSelect = function() {
417                 if ($scope.treedata) {
418                     for (var fi = 0; fi < $scope.treedata.length; fi++) {
419                         var fLevel = $scope.treedata[fi];
420                         if (fLevel.isSelected) {
421                             return true;
422                         }
423                         var sLevel = fLevel.child;
424                         if (sLevel) {
425                             for (var si = 0; si < sLevel.length; si++) {
426                                 if (sLevel[si].isSelected) {
427                                     return true;
428                                 }
429                                 var tLevel = sLevel[si].child;
430                                 if (tLevel) {
431                                     for (var ti = 0; ti < tLevel.length; ti++) {
432                                         if (tLevel[ti].isSelected) {
433                                             return true;
434                                         }
435                                     }
436                                 }
437                             }
438                         }
439                     }
440                 }
441                 return false;
442             }
443             // Populate the category list for category dropdown list
444             let getFunctionalMenu = () => {
445                 this.isLoadingTable = true;
446                 if (this.debug)
447                     $log.debug('getFunctionalMenu:init');
448
449                 functionalMenuService.getFunctionalMenuRole().then(role_res => {
450                     var menu_role_dict = {};
451                     if (this.debug)
452                         $log.debug('functionalMenuService:getFunctionalMenuRole:: getting result', role_res);
453
454                     for (var i in role_res) {
455                         // if first time appear in menu_role_dict
456                         if (!(role_res[i].menuId in menu_role_dict)) {
457                             menu_role_dict[role_res[i].menuId] = [role_res[i].roleId];
458                         } else {
459                             menu_role_dict[role_res[i].menuId].push(role_res[i].roleId);
460                         }
461                     }
462
463                     functionalMenuService.getManagedFunctionalMenuForNotificationTree().then(res => {
464                         if (this.debug)
465                             $log.debug('functionalMenuService:getManagedFunctionalMenuForNotificationTree:: getting result', res);
466                         var exclude_list = ['Favorites'];
467                         let actualData = [];
468                         $scope.functionalMenuRes = res;
469
470                         //Adding children and label attribute to all objects in res
471                         for (let i = 0; i < res.length; i++) {
472                             res[i].child = [];
473                             res[i].name = res[i].text;
474                             res[i].id = res[i].text;
475                             res[i].displayCheckbox = true;
476                             $scope.checkBoxObj = {
477                                 isAnyRoleSelected: false
478                             };
479                             res[i].roleId = menu_role_dict[res[i].menuId];
480                             res[i].onSelect = function() {
481                                 $scope.$apply(function() {
482                                     $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect();
483                                 })
484                             };
485
486                             if (res[i].roleId && res[i].roleId.length == _.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length) {
487                                 res[i].isSelected = true;
488                                 res[i].selected = true;
489                                 res[i].indeterminate = false;
490                             } else {
491                                 /*default*/
492                                 res[i].isSelected = false;
493                                 res[i].selected = false;
494                                 res[i].indeterminate = false;
495                             }
496                         }
497
498                         // Adding actual child items to children array in res
499                         // objects
500                         $scope.parentChildDict = {};
501                         $scope.parentChildRoleIdDict = {};
502                         for (let i = 0; i < res.length; i++) {
503                             let parentId = res[i].menuId;
504                             $scope.parentChildDict[parentId] = [];
505                             $scope.parentChildRoleIdDict[parentId] = [];
506                             for (let j = 0; j < res.length; j++) {
507                                 let childId = res[j].parentMenuId;
508                                 if (parentId === childId) {
509                                     res[i].child.push(res[j]);
510                                     $scope.parentChildDict[parentId].push(res[j].menuId);
511                                     //if res[j].roleId is defined
512                                     if (res[j].roleId) {
513                                         for (let k in res[j].roleId) {
514                                             $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]);
515                                         }
516
517                                     }
518                                 }
519                             }
520                         }
521                         //check if grand children exist
522                         for (var key in $scope.parentChildDict) {
523                             var child = $scope.parentChildDict[key];
524                             var isGrandParent = false;
525                             if (child.length > 0) {
526                                 for (var i in child) {
527                                     if ($scope.parentChildDict[child[i]].length > 0) {
528                                         isGrandParent = true;
529                                         break;
530                                     }
531                                 }
532                             }
533                             if (isGrandParent) {
534                                 for (var i in child) {
535                                     // if the child has children
536                                     if ($scope.parentChildDict[child[i]].length > 0) {
537                                         for (var j in $scope.parentChildRoleIdDict[child[i]]) {
538                                             if ($scope.parentChildRoleIdDict[key].indexOf($scope.parentChildRoleIdDict[child[i]][j]) === -1) {
539                                                 $scope.parentChildRoleIdDict[key].push($scope.parentChildRoleIdDict[child[i]][j]);
540                                             }
541                                         }
542                                     }
543                                 }
544                             }
545
546                         };
547
548                         // Sort the top-level menu items in order based on the column
549                         res.sort(function(a, b) {
550                             return a.column - b.column;
551                         });
552
553                         // Sort all the child in order based on the column
554                         for (let i = 0; i < res.length; i++) {
555                             res[i].child.sort(function(a, b) {
556                                 return a.column - b.column;
557                             });
558                         }
559
560                         //Forming actual parent items
561                         for (let i = 0; i < res.length; i++) {
562                             let parentId = res[i].parentMenuId;
563                             if (parentId === null) {
564                                 actualData.push(res[i]);
565                             }
566                         }
567                         var treedata = actualData[0].child;
568                         $scope.treedata = [];
569
570                         /*Remove favorite from the list */
571                         for (var i in treedata) {
572                             if (!(treedata[i].name.indexOf(exclude_list) > -1)) {
573                                 $scope.treedata.push(treedata[i])
574                             }
575                         }
576                         //setting b2b tree parameter
577                         $scope.settingTreeParam();
578
579                     }).catch(err => {
580                         $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err);
581                     }).finally(() => {
582                         this.isLoadingTable = false;
583                     })
584
585                 }).catch(err => {
586                     $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err);
587                 });
588             }
589
590
591             let getAppRoleIds = () => {
592                 $scope.notifObj = {
593                     isCategoriesFunctionalMenu: false
594                 };
595                 notificationService.getAppRoleIds().then(res => {
596                     if (this.debug)
597                         $log.debug('notificationService:getAppRoleIds:: getting result', res);
598                     res = res.data;
599                     let actualData = [];
600                     var app_id_name_list = {};
601                     $scope.checkBoxObj = {
602                         isAnyRoleSelected: false
603                     };
604                     for (let i = 0; i < res.length; i++) {
605                         if (!(res[i].appId in app_id_name_list)) {
606                             app_id_name_list[res[i].appId] = res[i].appName;
607                         }
608                         res[i].child = [];
609                         res[i].name = res[i].roleName;
610                         res[i].displayCheckbox = true;
611                         res[i].id = res[i].roleId;
612                         res[i].menuId = res[i].roleId;
613                         res[i].parentMenuId = res[i].appId;
614                         res[i].can_check = true;
615                         res[i].roleId = [res[i].roleId];
616                         res[i].onSelect = function() {
617                             $scope.$apply(function() {
618                                 $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect();
619                             })
620                         };
621                         /*assigning selected value*/
622                         if (res[i].roleId && res[i].roleId.length == _.intersection(res[i].roleId, $scope.roleObj.notificationRoleIds).length) {
623                             res[i].isSelected = true;
624                             res[i].selected = true;
625                             res[i].indeterminate = false;
626                         } else {
627                             /*default*/
628                             res[i].isSelected = false;
629                             res[i].selected = false;
630                             res[i].indeterminate = false;
631                         }
632                     }
633
634                     for (var app_id in app_id_name_list) {
635                         var new_res = {};
636                         new_res.child = [];
637                         new_res.name = app_id_name_list[app_id];
638                         new_res.id = app_id;
639                         new_res.displayCheckbox = true;
640                         new_res.menuId = app_id;
641                         new_res.parentMenuId = null;
642                         new_res.appId = null;
643                         new_res.can_check = true;
644                         new_res.roleId = null;
645                         new_res.onSelect = function() {
646                             $scope.$apply(function() {
647                                 $scope.newNotifModel.anyTreeItemSelected = $scope.checkTreeSelect();
648                             })
649                         };
650                         res.push(new_res);
651                     }
652                     $scope.parentChildRoleIdDict = {};
653                     //Adding actual child items to child array in res objects
654                     for (let i = 0; i < res.length; i++) {
655                         let parentId = res[i].menuId;
656                         $scope.parentChildRoleIdDict[parentId] = [];
657                         for (let j = 0; j < res.length; j++) {
658                             let childId = res[j].parentMenuId;
659                             if (parentId == childId) {
660                                 res[i].child.push(res[j]);
661                                 if (res[j].roleId) {
662                                     for (let k in res[j].roleId) {
663                                         $scope.parentChildRoleIdDict[parentId].push(res[j].roleId[k]);
664                                     }
665
666                                 }
667                             }
668                         }
669                     }
670                     //Forming actual parent items
671                     for (let i = 0; i < res.length; i++) {
672                         let parentId = res[i].parentMenuId;
673                         if (parentId === null) {
674                             actualData.push(res[i]);
675                         }
676                     }
677
678                     $scope.treedata = actualData;
679                     //setting correct parameters for b2b tree
680                     $scope.settingTreeParam();
681                 }).catch(err => {
682                     $log.error('FunctionalMenuCtrl:getFunctionalMenu:: error ', err);
683                 }).finally(() => {
684                     this.isLoadingTable = false;
685                 })
686             }
687             $scope.getFunctionalMenu = function() {
688                 $scope.treeTitle = "Functional Menu";
689                 getFunctionalMenu();
690             }
691             $scope.getAppRoleIds = function() {
692                 $scope.treeTitle = "Applications/Roles";
693                 getAppRoleIds();
694             }
695
696
697
698             $scope.settingTreeParam = function() {
699                 /**************first level****************/
700                 for (var fi = 0; fi < $scope.treedata.length; fi++) {
701                     var fLevel = $scope.treedata[fi];
702                     var sLevel = $scope.treedata[fi].child;
703                     var sLevelSelectedCount = 0;
704                     var sLevelChildNumber = 0
705                     if (fLevel.child.length == 0 && fLevel.roleId == null) {
706                         delete fLevel.child;
707                     } else if (sLevel) {
708                         /**************Second level****************/
709                         var sLevelDelArray = [];
710                         for (var si = 0; si < sLevel.length; si++) {
711                             var deletThisSLev = false;
712                             if (sLevel[si].child.length == 0 && sLevel[si].roleId == null) {
713                                 sLevel[si].displayCheckbox = false;
714                                 sLevelDelArray.push(sLevel[si].name);
715                                 sLevel[si].name = '';
716                                 sLevel[si].active = false;
717                                 delete sLevel[si].child;
718                             } else if (sLevel[si].child.length == 0) {
719                                 delete sLevel[si].child;
720                             } else {
721                                 /**************Third level****************/
722                                 var tLevel = sLevel[si].child;
723                                 var tLevelSelectedCount = 0;
724                                 var tLevelChildNumber = 0;
725                                 if (tLevel) {
726                                     var tLevelDelArray = [];
727                                     var tLevelLen = tLevel.length;
728                                     var tLevelRoleIdUndefined = 0;
729                                     for (var ti = 0; ti < tLevel.length; ti++) {
730                                         delete tLevel[ti].child;
731                                         if (tLevel[ti].roleId == null) {
732                                             tLevel[ti].displayCheckbox = false;
733                                             tLevelDelArray.push(tLevel[ti].name);
734                                             tLevel[ti].name = '';
735                                             tLevel[ti].active = false;
736                                             tLevelRoleIdUndefined++
737                                         } else {
738                                             if (tLevel[ti].isSelected)
739                                                 tLevelSelectedCount++;
740
741                                             if (tLevel[ti].displayCheckbox)
742                                                 tLevelChildNumber++;
743                                         }
744                                     }
745                                     if (tLevelRoleIdUndefined == tLevelLen)
746                                         deletThisSLev = true;
747                                     if (tLevelSelectedCount == tLevelChildNumber) {
748                                         sLevel[si].isSelected = true;
749                                         sLevel[si].indeterminate = false;
750                                         sLevel[si].active = true;
751                                     } else if (tLevelSelectedCount > 0) {
752                                         sLevel[si].indeterminate = true;
753                                         sLevel[si].active = true;
754                                     }
755
756                                     /*Cleanup unused third level items*/
757                                     for (var i = 0; i < tLevelDelArray.length; i++) {
758                                         var name = tLevelDelArray[i];
759                                         for (var ti = 0; ti < tLevel.length; ti++) {
760                                             if (name == tLevel[ti].text) {
761                                                 tLevel.splice(ti, 1);
762                                                 break;
763                                             }
764                                         }
765                                     }
766                                 }
767                             }
768                             if (deletThisSLev) { //remove the whole second level item if all it's child has no roleId
769                                 sLevel[si].displayCheckbox = false;
770                                 sLevelDelArray.push(sLevel[si].name);
771                                 sLevel[si].name = '';
772                                 sLevel[si].active = false;
773                             } else {
774                                 if (sLevel[si].isSelected)
775                                     sLevelSelectedCount++;
776                                 if (sLevel[si].displayCheckbox)
777                                     sLevelChildNumber++;
778                             }
779                         }
780                         if (sLevelSelectedCount == sLevelChildNumber && sLevelChildNumber != 0) {
781                             fLevel.isSelected = true;
782                             fLevel.indeterminate = false;
783                             fLevel.active = true;
784                         } else if (sLevelSelectedCount > 0) {
785                             fLevel.indeterminate = true;
786                             fLevel.active = true;
787                         } else {
788                             //fLevel.active=false;
789                             fLevel.indeterminate = false;
790                         }
791                         /*Cleanup unused second level items*/
792                         for (var i = 0; i < sLevelDelArray.length; i++) {
793                             var name = sLevelDelArray[i];
794                             for (var si = 0; si < sLevel.length; si++) {
795                                 if (name == sLevel[si].text) {
796                                     sLevel.splice(si, 1);
797                                     break;
798                                 }
799                             }
800                         }
801                     }
802                 }
803             }
804             init();
805             getFunctionalMenu();
806
807         }
808
809     }
810
811     userNotificationsModalCtrl.$inject = ['$scope', '$log', 'functionalMenuService', 'confirmBoxService', 'notificationService', '$modal', 'ngDialog', '$state', '$filter', 'items'];
812     angular.module('ecompApp').controller('userNotificationsModalCtrl', userNotificationsModalCtrl);
813
814 })();