nexus site path corrected
[portal.git] / ecomp-portal-FE / client / app / views / header / header.controller.js
1 /*-
2  * ================================================================================
3  * eCOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 'use strict';
21 (function () {
22         class HeaderCtrl {
23         constructor($log, $window, userProfileService, menusService, $scope, ECOMP_URL_REGEX, $cookies, $state) {
24             this.firstName = '';
25             this.lastName = '';
26             this.$log = $log;
27             this.menusService = menusService;
28             this.$scope = $scope;
29             this.favoritesMenuItems = '';
30             $scope.favoriteItemsCount = 0;
31             $scope.favoritesMenuItems = '';
32             $scope.showFavorites = false;
33             $scope.emptyFavorites = false;
34             $scope.favoritesWindow = false;
35
36             $scope.showNotification = true;
37
38             $scope.hideMenus = false;
39
40             $scope.menuItems = [];
41             $scope.activeClickSubMenu = {
42                 x: ''
43             }; 
44             $scope.activeClickMenu = {
45                 x: ''
46             };
47             $scope.megaMenuDataObject =[];
48             
49             this.isLoading = true;
50             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
51
52             var menuStructureConvert = function(menuItems) {
53                 $scope.megaMenuDataObjectTemp = [
54                     {
55                         text: "Manage/Functions",
56                         children: [],
57                     },
58                     {
59                         text: "Help",
60                         children: [{
61                                 restrictedApp: true,
62                             text:"Contact Us",
63                             url:""
64                         },
65                             {
66                                 text:"Get Access",
67                                 url:"root.access"
68                             }]
69                     }
70
71                 ];
72                 return $scope.megaMenuDataObjectTemp;
73             };
74             
75             var unflatten = function( array, parent, tree ){
76             
77                 tree = typeof tree !== 'undefined' ? tree : [];
78                 parent = typeof parent !== 'undefined' ? parent : { menuId: null };
79                 var children = _.filter( array, function(child){ return child.parentMenuId == parent.menuId; });
80                 
81                 if( !_.isEmpty( children )  ){
82                   if( parent.menuId === null ){
83                     tree = children;
84                   }else{
85                     parent['children'] = children
86                   }
87                   _.each( children, function( child ){ unflatten( array, child ) } );
88                 }
89             
90                 return tree;
91             }
92             
93                 var self = this;
94                 $scope.$on('handleUpdateUserInfo', function () {
95                     userProfileService.resetFunctionalMenuStaticInfo()
96                     .then(reset_res=> {
97                         userProfileService.getFunctionalMenuStaticInfo()
98                         .then(res=> {
99                             $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting Functional Menu Static Info init');
100                             if(res==null || res.firstName==null || res.firstName=='' || res.lastName==null || res.lastName=='' ){
101                                 $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: failed getting userinfo from shared context.. ');
102                                 $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting userinfo from session ');
103                                 userProfileService.getUserProfile()
104                                 .then(profile=> {
105                                     $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting userinfo from session success');
106                                     self.firstName = profile.firstName;
107                                     self.lastName = profile.lastName;                     
108                                     $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: user has the following roles: ' + profile.roles);
109                                 }).catch(err=> {
110                                     $log.error('Header Controller:: getUserProfile() failed: ' + err);
111                                 });
112                             }else{
113                                 $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting Functional Menu Static Info successfully',res);
114                                 self.firstName = res.firstName;
115                                 self.lastName = res.lastName;
116                                 $scope.contactUsURL = res.contact_us_link;
117                             }
118
119                             menusService.GetFunctionalMenuForUser()
120                             .then(jsonHeaderMenu=> {
121                                 $scope.menuItems = unflatten( jsonHeaderMenu );
122                                 $scope.megaMenuDataObject = $scope.menuItems;
123                             }).catch(err=> {
124                                 $scope.megaMenuDataObject = menuStructureConvert('');
125                                 $log.error('HeaderCtrl::GetFunctionalMenuForUser: HeaderCtrl json returned: ' + err);
126                             });      
127
128                             userProfileService.refreshUserBusinessCard();
129                             
130                         }).catch(err=> {
131                             $log.error('HeaderCtrl::getFunctionalMenuStaticInfo failed: ' + err);
132                         });
133                     }).catch(err=> {
134                         $log.error('HeaderCtrl::resetFunctionalMenuStaticInfo failed: ' + err);
135                     })
136
137
138                 });
139
140             userProfileService.getFunctionalMenuStaticInfo()
141             .then(res=> {
142                 $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting Functional Menu Static Info init');
143                 if(res==null || res.firstName==null || res.firstName=='' || res.lastName==null || res.lastName=='' ){
144                         $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: failed getting userinfo from shared context.. ');
145                         $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting userinfo from session ');
146                         userProfileService.getUserProfile()
147                     .then(profile=> {
148                         $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting userinfo from session success');
149                         this.firstName = profile.firstName;
150                         this.lastName = profile.lastName;                     
151                         $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: user has the following roles: ' + profile.roles);
152                     }).catch(err=> {
153                         $log.error('Header Controller:: getUserProfile() failed: ' + err);
154                     });
155                 }else{
156                         $log.info('HeaderCtrl::getFunctionalMenuStaticInfo: getting Functional Menu Static Info successfully',res);
157                         this.firstName = res.firstName;
158                         this.lastName = res.lastName;                                     
159                         $scope.contactUsURL = res.contact_us_link;
160                 }
161
162                 menusService.GetFunctionalMenuForUser()
163                 .then(jsonHeaderMenu=> {
164                         $scope.menuItems = unflatten( jsonHeaderMenu );
165                         $scope.megaMenuDataObject = $scope.menuItems;
166                 }).catch(err=> {
167                         $scope.megaMenuDataObject = menuStructureConvert('');
168                         $log.error('HeaderCtrl::GetFunctionalMenuForUser: HeaderCtrl json returned: ' + err);
169                 });      
170                 
171             }).catch(err=> {
172                 $log.error('HeaderCtrl::getFunctionalMenuStaticInfo failed: ' + err);
173             });
174             
175
176             $scope.loadFavorites = function () {
177                 $scope.hideMenus = false;
178                 $log.debug('HeaderCtrl::loadFavorites: loadFavorites has happened.');
179                 if ($scope.favoritesMenuItems == '') {
180                     generateFavoriteItems();
181                     $log.debug('HeaderCtrl::loadFavorites: loadFavorites is calling generateFavoriteItems()');
182                 } else {
183                     $log.debug('HeaderCtrl::loadFavorites: loadFavorites is NOT calling generateFavoriteItems()');
184                 }
185             }
186
187             $scope.goToUrl = (item) =>  {
188                 $log.info('HeaderCtrl::goToUrl has started');
189                 let url = item.url;
190                 let restrictedApp = item.restrictedApp;
191                 if (!url) {
192                     $log.info('HeaderCtrl::goToUrl: No url found for this application, doing nothing..');
193                     return;
194                 }
195                 if (restrictedApp) {
196                     $window.open(url, '_blank');
197                 } else {
198                         if(item.url=="getAccess" || item.url=="contactUs"){
199                             // if (url = window.location.href)
200                                 $state.go("root."+url);
201                                 var tabContent = { id: new Date(), title: 'Home', url: item.url };
202                         $cookies.putObject('addTab', tabContent );
203                         } else {
204                         var tabContent = { id: new Date(), title: item.text, url: item.url };
205                         $cookies.putObject('addTab', tabContent );
206                     }
207                     $log.debug('HeaderCtrl::goToUrl: url = ', url);
208                 }
209                 $scope.hideMenus = true;
210             }
211             
212             
213             
214             $scope.submenuLevelAction = function(index, column) {
215                 if ($scope.favoritesMenuItems == '') {
216                     generateFavoriteItems();
217                     $log.debug('HeaderCtrl::submenuLevelAction: submenuLevelAction is calling generateFavoriteItems()');
218                 }
219                 if (index=='Favorites' && $scope.favoriteItemsCount != 0) {
220                     $log.debug('HeaderCtrl::submenuLevelAction: Showing Favorites window');
221                     $scope.favoritesWindow = true;
222                     $scope.showFavorites = true;
223                     $scope.emptyFavorites = false;
224                 }
225                 if (index=='Favorites' && $scope.favoriteItemsCount == 0) {
226                     $log.debug('HeaderCtrl::submenuLevelAction: Hiding Favorites window in favor of No Favorites Window');
227                     $scope.favoritesWindow = true;
228                     $scope.showFavorites = false;
229                     $scope.emptyFavorites = true;
230                 }
231                 if (index!='Favorites' ) {
232                     $scope.favoritesWindow = false;
233                     $scope.showFavorites = false;
234                     $scope.emptyFavorites = false;
235                 }
236
237             };
238             
239             $scope.hideFavoritesWindow = function() {
240                 $scope.showFavorites = false;
241                 $scope.emptyFavorites = false;
242             }
243             
244             $scope.isUrlFavorite = function (menuId) {
245                 var jsonMenu =  JSON.stringify($scope.favoritesMenuItems);
246                 var isMenuFavorite =  jsonMenu.indexOf('menuId\":' + menuId);
247                 if (isMenuFavorite==-1) {
248                     return false;
249                 } else {
250                     return true;
251                 }
252
253             }
254             
255             let generateFavoriteItems  = () => {
256                 menusService.getFavoriteItems()
257                     .then(favorites=> {
258                         $scope.favoritesMenuItems = favorites;
259                         $scope.favoriteItemsCount = Object.keys(favorites).length;
260                         $log.info('HeaderCtrl.getFavoriteItems:: number of favorite menus: ' + $scope.favoriteItemsCount);
261                     }).catch(err=> {
262                         $log.error('HeaderCtrl.getFavoriteItems:: Error retrieving Favorites menus: ' + err);
263                 });
264             }
265
266            $scope.setAsFavoriteItem =  function(event, menuId){
267                var jsonMenuID = angular.toJson({'menuId': + menuId });
268                $log.debug('HeaderCtrl::setFavoriteItems: ' + jsonMenuID  + " - " +  event.target.id);
269
270                menusService.setFavoriteItem(jsonMenuID)
271                .then(() => {
272                    angular.element('#' + event.target.id).css('color', '#fbb313');
273                    generateFavoriteItems();
274                }).catch(err=> {
275                    $log.error('HeaderCtrl::setFavoriteItems:: API setFavoriteItem error: ' + err);
276                });
277            };
278
279             $scope.removeAsFavoriteItem =  function(event, menuId){
280                 $log.debug('-----------------------------removeAsFavoriteItem: ' + menuId + " - " +  event.target.id);
281                 menusService.removeFavoriteItem(menuId)
282                 .then(() => {
283                     angular.element('#' + event.target.id).css('color', '#666666');
284                     generateFavoriteItems();
285                 }).catch(err=> {
286                     $log.error('HeaderCtrl::removeAsFavoriteItem: API removeFavoriteItem error: ' + err);
287                 });
288             };
289
290             $scope.goToPortal = (headerText, url) => {
291                 if (!url) {
292                     $log.info('HeaderCtrl::goToPortal: No url found for this application, doing nothing..');
293                     return;
294                 }
295                 if (!ECOMP_URL_REGEX.test(url)) {
296                     url = 'http://' + url;
297                 }
298
299                 if(headerText.startsWith("vUSP")) {
300                         window.open(url, '_blank');
301                 }
302                 else {
303                         var tabContent = { id: new Date(), title: headerText, url: url };
304                         $cookies.putObject('addTab', tabContent );
305                 }
306             };
307
308         }
309     }
310     class LoginSnippetCtrl {
311         constructor($log, $scope, $cookies, $timeout, userProfileService, sessionService,ngDialog) {
312             $scope.firstName="";
313             $scope.lastName="";
314             
315             $scope.allAppsLogout = function(){
316                 
317                 var cookieTabs = $cookies.getObject('visInVisCookieTabs');
318                 if(cookieTabs!=null){
319                         for(var t in cookieTabs){
320                         
321                                 var url = cookieTabs[t].content;
322                                 if(url != "") {
323                                         sessionService.logout(url);
324                         }
325                         }
326                 }
327                 // wait for individular applications to logoutout before the portal logout
328                 $timeout(function() {
329                         window.location = "logout.htm";
330                 }, 2000);
331             }
332             
333             $scope.openEditUserModal = function(){
334                 
335                 var data = {
336                                 loginId : $scope.loginSnippetUserId,
337                         updateRemoteApp : false,
338                         appId : $scope.selectedApp!=null?$scope.selectedApp.id:''
339                 }
340                 var modalInstance = ngDialog.open({
341                     templateUrl: 'app/views/header/user-edit/edit-user.tpl.html',
342                     controller: 'editUserController',
343                     data: data,
344                     resolve: {
345                         message: function message() {
346                             var message = {
347                                 type: 'Contact',
348                             };
349                             return message;
350                         }
351                     }
352                 }).closePromise.then(needUpdate => {
353                     //updateContactUsTable();
354                     });       
355             
356             }
357                         
358             try {
359                 userProfileService.getFunctionalMenuStaticInfo()
360                 .then(res=> {
361                   $log.info('HeaderCtrl::LoginSnippetCtrl: Login information: ' + JSON.stringify(res));
362                   $scope.firstName = res.firstName;
363                   $scope.lastName = res.lastName;
364                   $scope.loginSnippetEmail = res.email;
365                   $scope.loginSnippetUserId = res.userId;
366                   $scope.lastLogin = res.last_login;
367                 }).catch(err=> {
368                   $log.error('HeaderCtrl::LoginSnippetCtrl: User Profile error: ' + err);
369                 });
370             } catch (err) {
371                 $log.error('HeaderCtrl::LoginSnippetCtrl:getFunctionalMenuStaticInfo failed: ' + err);
372             }
373
374             $scope.$on('refreshUserBusinessCard', function () {
375                 try {
376                     userProfileService.getFunctionalMenuStaticInfo()
377                     .then(res=> {
378                     $log.info('HeaderCtrl::LoginSnippetCtrl: Login information: ' + JSON.stringify(res));
379                     $scope.firstName = res.firstName;
380                     $scope.lastName = res.lastName;
381                     $scope.loginSnippetEmail = res.email;
382                     $scope.loginSnippetUserId = res.userId;
383                     $scope.lastLogin = res.last_login;
384                     }).catch(err=> {
385                     $log.error('HeaderCtrl::LoginSnippetCtrl: User Profile error: ' + err);
386                     });
387                 } catch (err) {
388                     $log.error('HeaderCtrl::LoginSnippetCtrl:getFunctionalMenuStaticInfo failed: ' + err);
389                 }
390             });
391
392
393         }        
394     }
395     class NotificationCtrl{
396         constructor($log, $scope, $cookies, $timeout, sessionService) {
397                  $scope.notifications=[];
398              for(var i=0;i<6;i++){
399                  var data ={
400                                  content:'Notification '+i,
401                                  time:'10:0'+i+'AM'
402                  };
403                  $scope.notifications.push(data);
404              }      
405              
406              $scope.deleteNotification = function(index){
407                 
408                  $scope.notifications.splice(index,1);
409              }
410         }
411     }
412     NotificationCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout','userProfileService', 'sessionService'];
413     LoginSnippetCtrl.$inject = ['$log', '$scope', '$cookies', '$timeout','userProfileService', 'sessionService','ngDialog'];
414     HeaderCtrl.$inject = ['$log', '$window', 'userProfileService', 'menusService', '$scope', 'ECOMP_URL_REGEX','$cookies','$state'];
415     angular.module('ecompApp').controller('HeaderCtrl', HeaderCtrl);
416     angular.module('ecompApp').controller('loginSnippetCtrl', LoginSnippetCtrl);
417     angular.module('ecompApp').controller('notificationCtrl', NotificationCtrl);
418
419 })();