HTTPS calls into SDC
[portal.git] / ecomp-portal-FE-common / client / app / views / header / header.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 (function () {
40         class HeaderCtrl {
41     constructor($log, $window, $translate, translateService,userProfileService, menusService, $scope, ECOMP_URL_REGEX, $cookies, $state,auditLogService,notificationService,ngDialog,$modal) {
42       this.firstName = '';
43       this.lastName = '';
44       this.$log = $log;
45       this.menusService = menusService;
46       this.$scope = $scope;
47       this.favoritesMenuItems = '';
48       $scope.cur_lang = '';
49       $scope.langList = []
50       $scope.favoriteItemsCount = 0;
51       $scope.favoritesMenuItems = '';
52       $scope.showFavorites = false;
53       $scope.emptyFavorites = false;
54       $scope.favoritesWindow = false;
55       $scope.notificationCount=0;
56       $scope.showNotification = true;
57       // get all languages
58       var loginId = sessionStorage.getItem('userId')
59       translateService.getCurrentLang(loginId).then(res => {
60         $scope.cur_lang = res.languageAlias
61         $translate.use($scope.cur_lang);
62       })
63       translateService.getLangList().then(res => {
64         $scope.langList = res.languageList
65       })
66       // switch language
67       $scope.switching = function(lang) {
68         $translate.use(lang);
69         var langs = $scope.langList
70         var langId = ''
71         var selectedLang = langs.find(function(item) {
72           return item.languageAlias === lang;
73         });
74         langId = selectedLang.languageId
75         var loginId = sessionStorage.getItem('userId')
76         translateService.saveSelectedLang(loginId, {'languageId': langId}).then(res => {
77           window.location.reload();
78         })
79       }
80       $scope.cur_lang = $translate.use();
81
82             $scope.hideMenus = false;
83
84             $scope.menuItems = [];
85             $scope.activeClickSubMenu = {
86                 x: ''
87             }; 
88             $scope.activeClickMenu = {
89                 x: ''
90             };
91             $scope.megaMenuDataObject =[];
92             $scope.notificationCount= notificationService.notificationCount;
93             this.isLoading = true;
94             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
95             
96             var unflatten = function( array, parent, tree ){
97             
98                 tree = typeof tree !== 'undefined' ? tree : [];
99                 parent = typeof parent !== 'undefined' ? parent : { menuId: null };
100                 var children = _.filter( array, function(child){ return child.parentMenuId == parent.menuId; });
101                 
102                 if( !_.isEmpty( children )  ){
103                   if( parent.menuId === null ){
104                     tree = children;
105                   }else{
106                     parent['children'] = children
107                   }
108                   _.each( children, function( child ){ unflatten( array, child ) } );
109                 }
110             
111                 return tree;
112             }
113             
114             userProfileService.getFunctionalMenuStaticInfo()
115             .then(res=> {
116                 if(res==null || res.firstName==null || res.firstName=='' || res.lastName==null || res.lastName=='' ){
117                         $log.info('HeaderCtrl: failed to get all required data, trying user profile');
118                         userProfileService.getUserProfile()
119                     .then(profile=> {
120                         this.firstName = profile.firstName;
121                         this.lastName = profile.lastName;                     
122                     }).catch(err=> {
123                         $log.error('Header Controller:: getUserProfile() failed: ' + err);
124                     });
125                 } else {
126                         this.firstName = res.firstName;
127                         this.lastName = res.lastName;                                     
128                 }
129
130                 menusService.GetFunctionalMenuForUser()
131                 .then(jsonHeaderMenu=> {
132                         $scope.menuItems = unflatten( jsonHeaderMenu );
133                         $scope.megaMenuDataObject = $scope.menuItems;
134                 }).catch(err=> {
135                         $log.error('HeaderCtrl::GetFunctionalMenuForUser: HeaderCtrl json returned: ' + err);
136                 });      
137                 
138             }).catch(err=> {
139                 $log.error('HeaderCtrl::getFunctionalMenuStaticInfo failed: ' + err);
140             });
141             
142           //store audit log
143             $scope.auditLog = function(app,type) {
144                 var comment = 'type: '+type+ ',title: '+app.text+",url: "+app.url;
145                         auditLogService.storeAudit(app.appid,'functional',comment);
146                 };
147
148             $scope.loadFavorites = function () {
149                 $scope.hideMenus = false;
150                 if ($scope.favoritesMenuItems == '') {
151                     generateFavoriteItems();
152                 }
153             }
154
155             $scope.goToUrl = (item) =>  {
156                 let url = item.url;
157                 let restrictedApp = item.restrictedApp;
158                 if (!url) {
159                     $log.warn('HeaderCtrl::goToUrl: No url found for this application, doing nothing..');
160                     return;
161                 }
162                 if (restrictedApp) {
163                     $window.open(url, '_blank');
164                 } else {
165                         if(item.url=="getAccess" || item.url=="contactUs"){
166                                 $state.go("root."+url);
167                         } else {
168                         var tabContent = { id: new Date(), title: item.text, url: item.url,appId:item.appid };
169                         $cookies.putObject('addTab', tabContent );
170                     }
171                 }
172                 $scope.hideMenus = true;
173             }
174             
175             
176             
177             $scope.submenuLevelAction = function(index, column) {           
178                 if (index=='Favorites' && $scope.favoriteItemsCount != 0) {
179                     $scope.favoritesWindow = true;
180                     $scope.showFavorites = true;
181                     $scope.emptyFavorites = false;
182                 }
183                 if (index=='Favorites' && $scope.favoriteItemsCount == 0) {
184                     $scope.favoritesWindow = true;
185                     $scope.showFavorites = false;
186                     $scope.emptyFavorites = true;
187                 }
188                 if (index!='Favorites' ) {
189                     $scope.favoritesWindow = false;
190                     $scope.showFavorites = false;
191                     $scope.emptyFavorites = false;
192                 }
193             };
194             
195             $scope.hideFavoritesWindow = function() {
196                 $scope.showFavorites = false;
197                 $scope.emptyFavorites = false;
198             }
199             
200             $scope.isUrlFavorite = function (menuId) {
201                 var jsonMenu =  JSON.stringify($scope.favoritesMenuItems);
202                 var isMenuFavorite =  jsonMenu.indexOf('menuId\":' + menuId);
203                 if (isMenuFavorite==-1) {
204                     return false;
205                 } else {
206                     return true;
207                 }
208             }
209             
210             /*Getting Ecomp portal Title*/
211
212             let getEcompPortalTitle  = () => {
213                 menusService.getEcompPortalTitle()
214                 .then(title=> {
215                         $scope.ecompTitle = title.response;
216                 }).catch(err=> {
217                         $log.error('HeaderCtrl.getEcompPortalTitle:: Error retrieving ECMOP portal title: ' + err);
218                 });
219             }
220             getEcompPortalTitle();
221             
222             let generateFavoriteItems  = () => {
223                 menusService.getFavoriteItems()
224                     .then(favorites=> {
225                         $scope.favoritesMenuItems = favorites;
226                         $scope.favoriteItemsCount = Object.keys(favorites).length;
227                     }).catch(err=> {
228                         $log.error('HeaderCtrl.getFavoriteItems:: Error retrieving Favorites menus: ' + err);
229                 });
230             }
231
232            $scope.setAsFavoriteItem =  function(event, menuId){
233                var jsonMenuID = angular.toJson({'menuId': + menuId });
234                menusService.setFavoriteItem(jsonMenuID)
235                .then(() => {
236                    angular.element('#' + event.target.id).css('color', '#fbb313');
237                    generateFavoriteItems();
238                }).catch(err=> {
239                    $log.error('HeaderCtrl::setFavoriteItems:: API setFavoriteItem error: ' + err);
240                });
241            };
242
243             $scope.removeAsFavoriteItem =  function(event, menuId){
244                 menusService.removeFavoriteItem(menuId)
245                 .then(() => {
246                     angular.element('#' + event.target.id).css('color', '#666666');
247                     generateFavoriteItems();
248                 }).catch(err=> {
249                     $log.error('HeaderCtrl::removeAsFavoriteItem: API removeFavoriteItem error: ' + err);
250                 });
251             };
252
253             $scope.goToPortal = (headerText, url) => {
254                 if (!url) {
255                     $log.warn('HeaderCtrl::goToPortal: No url found for this application, doing nothing..');
256                     return;
257                 }
258                 if (!ECOMP_URL_REGEX.test(url)) {
259                     url = 'https://' + url;
260                 }
261
262                 if(headerText.startsWith("vUSP")) {
263                         window.open(url, '_blank');//, '_self'
264                 }
265                 else {
266                         var tabContent = { id: new Date(), title: headerText, url: url };
267                         $cookies.putObject('addTab', tabContent );
268                 }
269             };
270             
271             $scope.editProfile = () => {
272                 let data = null;
273                
274                 ngDialog.open({
275                     templateUrl: 'app/views/header/profile-edit-dialogs/profile-edit.modal.html',
276                     controller: 'EditProfileModalCtrl',
277                     controllerAs: 'profileDetail',
278                     data: ''
279                 }).closePromise.then(needUpdate => {
280                     if(needUpdate.value === true){
281                         updateTableData();
282                     }
283                 });
284             };
285         }
286     }
287     class LoginSnippetCtrl {
288         constructor($log, $scope, $cookies, $timeout, userProfileService, sessionService) {
289             $scope.firstName="";
290             $scope.lastName="";
291             $scope.displayUserAppRoles=false; 
292             $scope.allAppsLogout = function(){
293                 
294                 var cookieTabs = $cookies.getObject('visInVisCookieTabs');
295                 if(cookieTabs!=null){
296                         for(var t in cookieTabs){
297                         
298                                 var url = cookieTabs[t].content;
299                                 if(url != "") {
300                                         sessionService.logout(url);
301                         }
302                         }
303                 }
304                 // wait for individual applications to log out before the portal logout
305                 $timeout(function() {
306                         window.location = "logout.htm";
307                 }, 2000);
308             }
309             
310             
311             try {
312                 userProfileService.getFunctionalMenuStaticInfo()
313                 .then(res=> {
314                   $scope.firstName = res.firstName;
315                   $scope.lastName = res.lastName;
316                   $scope.loginSnippetEmail = res.email;
317                   $scope.loginSnippetUserid = res.userId;
318                   $scope.lastLogin = Date.parse(res.last_login);
319                 }).catch(err=> {
320                   $log.error('HeaderCtrl::LoginSnippetCtrl: failed in getFunctionalMenuStaticInfo: ' + err);
321                 });
322             } catch (err) {
323                 $log.error('HeaderCtrl::LoginSnippetCtrl caught exception: ' + err);
324             }
325             
326             $scope.getUserApplicationRoles= function(){
327                   $scope.userapproles = [];
328                   if($scope.displayUserAppRoles)
329                                 $scope.displayUserAppRoles = false;
330                                  else
331                                         $scope.displayUserAppRoles = true;
332                   
333                         userProfileService.getUserAppRoles($scope.loginSnippetUserid)
334                           .then(res=>{
335                                 
336                  for(var i=0;i<res.length;i++){                                 
337                         var userapprole ={
338                                 App:res[i].appName,
339                                 Roles:res[i].roleNames, 
340                         };                      
341                         $scope.userapproles.push(userapprole); 
342                  }
343                  
344                 });
345                 
346           }
347         }        
348     }
349     class NotificationCtrl{
350         constructor($log, $scope, $cookies, $timeout, sessionService,notificationService,$interval,ngDialog,$modal) {
351                  $scope.notifications=[];   
352                  var intervalPromise = null;
353              $scope.notificationCount= notificationService.notificationCount;
354              
355              $scope.getNotification = function(){                
356                  notificationService.getNotification()
357                  .then(res=> {
358                         notificationService.decrementRefreshCount();
359                         var count = notificationService.getRefreshCount();
360                         if (res==null || res.data==null || res.data.message!='success') {
361                                 $log.error('NotificationCtrl::updateNotifications: failed to get notifications');
362                                 if (intervalPromise != null)
363                                         $interval.cancel(intervalPromise);
364                         } else if(count<=0){
365                                 if (intervalPromise != null)
366                                         $interval.cancel(intervalPromise);
367                         } else {
368                                 $scope.notifications = [];
369                                 notificationService.setNotificationCount(res.data.response.length);
370                                 for(var i=0;i<res.data.response.length;i++){
371                                         var data = res.data.response[i];                                        
372                                         var notification ={
373                                                 id:data.notificationId,
374                                                 msgHeader:data.msgHeader,
375                                                 message:data.msgDescription,
376                                                 msgSource:data.msgSource,
377                                                 time:data.createdDate,
378                                                 priority:data.priority,
379                                                 notificationHyperlink:data.notificationHyperlink
380                                         };
381                                         $scope.notifications.push(notification);       
382                                      }  
383                         }       
384                  }).catch(err=> {
385                         $log.error('NotificationCtrl::getNotification: caught exception: ' + err);
386                         if (intervalPromise != null)
387                                 $interval.cancel(intervalPromise);
388                  });      
389              }
390              $scope.getNotification();
391              function updateNotifications() {
392                  $scope.getNotification();
393              }
394              $scope.start = function(rate) {
395                                 // stops any running interval to avoid two intervals running at the same time
396                                 $scope.stop();  
397                                 // store the interval promise
398                                 intervalPromise = $interval(updateNotifications, rate);
399                          };
400
401                          $scope.stop = function() {
402                                 $interval.cancel(intervalPromise);
403                          };
404                          
405                          $scope.showDetailedJsonMessage=function (selectedAdminNotification) {
406                          notificationService.getMessageRecipients(selectedAdminNotification.id).then(res =>{
407                      $scope.messageRecipients = res;
408                                  var messageObject=JSON.parse(selectedAdminNotification.message);
409                                  var modalInstance = $modal.open({
410                             templateUrl: 'app/views/user-notifications-admin/user.notifications.json.details.modal.page.html',
411                             controller: 'userNotificationCtrl',
412                             sizeClass: 'modal-large', 
413                             resolve: {
414                                                 items: function () {
415                                                         var items = {
416                                                                    title:    '',
417                                                     selectedAdminNotification:selectedAdminNotification,messageObject:messageObject,messageRecipients:$scope.messageRecipients
418                                                         
419                                                         };
420                                                   return items;
421                                                 }
422                                 }
423                         })
424                      
425          
426          }).catch(err => {
427             $log.error('userNotificationsCtrl:getMessageRecipients:: error ', err);
428             $scope.isLoadingTable = false;
429         });
430                  };
431                          
432                         notificationService.getNotificationRate().then(res=> {
433                 if (res == null || res.response == null) {
434                         $log.error('NotificationCtrl: failed to notification update rate or duration, check system.properties file.');
435                 } else {
436                         var rate = parseInt(res.response.updateRate);
437                                         var duration = parseInt(res.response.updateDuration);
438                                         notificationService.setMaxRefreshCount(parseInt(duration/rate)+1);
439                                         notificationService.setRefreshCount(notificationService.maxCount);
440                                 if (rate != NaN && duration != NaN) {
441                                                 $scope.updateRate=rate;
442                                                 $scope.start($scope.updateRate);
443                                 }                               
444                 }
445             }).catch(err=> {
446                 $log.error('NotificationCtrl: getNotificationRate() failed: ' + err);
447             });
448              
449              $scope.deleteNotification = function(index){
450                  if ($scope.notifications[index].id == null || $scope.notifications[index].id == '') {
451                         $log.error('NotificationCtrl: failed to delete Notification.');
452                         return;
453                  }
454                  notificationService.setNotificationRead($scope.notifications[index].id);
455                  $scope.notifications.splice(index,1);
456                  notificationService.setNotificationCount($scope.notifications.length);          
457              }
458         }
459     }
460     
461     NotificationCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout', 'sessionService','notificationService','$interval','ngDialog','$modal'];
462     LoginSnippetCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout','userProfileService', 'sessionService'];
463     HeaderCtrl.$inject = ['$log', '$window', '$translate', 'translateService', 'userProfileService', 'menusService', '$scope', 'ECOMP_URL_REGEX','$cookies','$state','auditLogService','notificationService','ngDialog','$modal'];
464     angular.module('ecompApp').controller('HeaderCtrl', HeaderCtrl);
465     angular.module('ecompApp').controller('loginSnippetCtrl', LoginSnippetCtrl);
466     angular.module('ecompApp').controller('notificationCtrl', NotificationCtrl);
467 })();