[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-FE-common / client / app / views / dashboard / dashboard.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
22 function _classCallCheck(instance, Constructor) {
23         if (!(instance instanceof Constructor)) {
24                 throw new TypeError('Cannot call a class as a function');
25         }
26 }
27
28 (function() {
29         var HTTP_PROTOCOL_RGX = /https?:\/\//;
30
31         var DashboardCtrl = function DashboardCtrl(conf, applicationsService, $log,
32                         $window, userProfileService, $scope, $cookies, $timeout, $interval, 
33                         $modal, $state, beReaderService, dashboardService, confirmBoxService, 
34                         auditLogService,ngDialog, $compile, widgetsCatalogService) {
35
36                 this.conf = conf;       
37                 var _this = this;
38
39                 _classCallCheck(this, DashboardCtrl);
40
41                 // activate spinner
42                 this.isLoading = true;
43                 this.isCommError = false;
44                 $scope.getUserAppsIsDone = false;
45                 this.userProfileService = userProfileService;
46                 $scope.demoNum = 1;
47                 $scope.event_content_show = false;
48                 $scope.widgetData = [];
49                 $scope.activateThis = function(ele){
50                          $compile(ele.contents())($scope);
51                          $scope.$apply();
52                 };
53
54                 $scope.editWidgetModalPopup = function(availableData, resourceType) {
55                         $scope.editData = JSON.stringify(availableData);
56                         $scope.availableDataTemp = $scope.availableData;
57                         ngDialog.open({
58                                         templateUrl : 'app/views/dashboard/dashboard-widget-manage.html',
59                                         controller : 'CommonWidgetController',
60                                         resolve : {
61                                                 message : function message() {
62                                                         var message = {
63                                                                 type : resourceType,
64                                                                 availableData : $scope.editData
65                                                         };
66                                                         return message;
67                                                 }
68                                         }
69                                 }).closePromise.then(needUpdate => {    
70                                         if(resourceType=='NEWS'){
71                                                 $scope.updateNews();
72                                         }else if(resourceType=='EVENTS'){
73                                                 $scope.updateEvents();
74                                         }else if(resourceType=='IMPORTANTRESOURCES'){
75                                                 $scope.updateImportRes();
76                                         }
77                   });           
78                 };
79                 
80                 $scope.editWidgetParameters = function(widgetId) {
81                         let data = {
82                 widgetId: widgetId
83             }
84                         ngDialog.open({
85                                         templateUrl : 'app/views/dashboard/dashboard-widget-parameter-manage.html',
86                                         controller : 'WidgetParameterController',
87                                         data: data
88                                 }).closePromise.then(needUpdate => {    
89                                                 
90                   });           
91                 };
92                 
93                 $scope.sort_options = [        
94                                        {index: 0, value: 'N', title: 'Name'},
95                                        {index: 1, value: 'L', title: 'Last used'},
96                                        {index: 2, value: 'F', title: 'Most used'},
97                                        {index: 3, value: 'M', title: 'Manual'}                                 
98                                    ]; 
99                 
100                 $scope.selectedSortTypeChanged = function(userAppSortTypePref) {
101                         $scope.appsViewData = [];
102                         $scope.appsView = [];
103                         
104                         $scope.sort_type = userAppSortTypePref;
105                         
106                         applicationsService
107                         .getAppsOrderBySortPref(userAppSortTypePref)
108                                 .then(function(res) {
109                                         _this.apps = res;                       
110                                         $scope.applyPresentationDetailsToApps(_this.apps);                              
111                         })      
112                         applicationsService
113                         .saveAppsSortTypePreference($scope.selectedSortType)
114                                 .then(function(res) {
115                                         // Nothing to do
116                                 })
117                 
118                 }
119                 $scope.$watch('selectedSortType.value', (newVal, oldVal) => {
120                         for(var i=0;i<$scope.sort_options.length;i++){
121                         if($scope.sort_options[i].value==newVal){
122                         $scope.selectedSortType=angular.copy($scope.sort_options[i]);;
123                         }
124                         }
125                         });
126                 
127                 $scope.restoreSortSelected = function(){
128                         confirmBoxService.confirm("Restore the default size and position of all widgets?").then(
129                                 function(confirmed){
130                                         var checkConfirm = confirmed;
131                                         if(checkConfirm === true){
132                                         applicationsService
133                                         .delWidgetsSortPref($scope.widgetsViewData).then(function(){
134                                                 $state.reload();
135                                         });
136                                         }
137                                 });
138                 /*      if(confirm('Restore the default size and position of all widgets?') == true)
139                                 {
140                         applicationsService
141                         .delWidgetsSortPref($scope.widgetsViewData).then(function(){
142                                 $state.reload();
143                         })
144                                 }*/
145                                 
146                 }
147                 
148                 $scope.applyPresentationDetailsToApps = function(appsReturned) {
149                         var rowNo = 0;
150                         for (var i = 0; i < _this.apps.length; i++) {
151                                 $scope.appsView[i] = {
152                                         sizeX : 1,
153                                         sizeY : 1,
154                                         headerText : '',
155                                         subHeaderText : '',
156                                         imageLink : '',
157                                         order : '',
158                                         url : '',
159                                         appid: '',
160                                 };
161                                 $scope.appsView[i].headerText = appsReturned[i].name;
162                                 $scope.appsView[i].subHeaderText = appsReturned[i].notes;
163                                 let imgLnk = '';
164                                 if (appsReturned[i].imageUrl)
165                                         imgLnk = conf.api.appThumbnail.replace(':appId', appsReturned[i].id);
166                                 //$log.debug('DashboardCtlr::applyPresn: imgLink = ' + imgLnk);
167                                 $scope.appsView[i].imageLink = imgLnk;
168                                 $scope.appsView[i].order = appsReturned[i].order;
169                                 $scope.appsView[i].url = appsReturned[i].url;
170                                 $scope.appsView[i].restrictedApp = appsReturned[i].restrictedApp;
171                                 $scope.appsView[i].appid = appsReturned[i].id;
172                         }
173                         $scope.appsView[_this.apps.length] = {
174                                         addRemoveApps : true,
175                                         sizeX : 1,
176                                         sizeY : 1,
177                                         headerText : 'Add/Remove Applications',
178                                         subHeaderText : '',
179                                         imageLink : 'assets/images/cloud.png',
180                                         order : '',
181                                         restrictedApp : false,
182                                         url : '',
183                         };
184                         if($scope.appsView.length>6){                                                                                                   
185                                 $(".dashboard-boarder").css({
186                                         "height" : "400px"
187                                 });
188                         }else{
189                                 $(".dashboard-boarder").css({
190                                         "height" : "210px"
191                                 });
192                         }
193                         
194                         if ($scope.appsView != undefined
195                                         && $scope.appsView != null
196                                         && $scope.appsView.length > 0) {
197                                 $scope.appsViewData = $scope.appsView;
198                         }
199                 }
200                 
201 $scope.widgetsView = [];
202                 
203                 $scope.applyPresentationDetailsToWidgets = function(widgetsReturned){
204                  var rowNo = 0;
205                  for (var i = 0; i < widgetsReturned.length; i++) {
206                                 $scope.widgetsView[i] = {
207                                         sizeX : '',
208                                         sizeY :'',
209                                         headerText:'',
210                                         widgetText:'',
211                                         widgetIdentifier : '',
212                                         url : '',
213                                         widgetid: '',
214                                         attrb:'',
215                                         row:'',
216                                         col:'',
217                                 };
218                                 $scope.widgetsView[i].widgetid = widgetsReturned[i].id;
219                                 $scope.widgetsView[i].headerText = widgetsReturned[i].headerName;
220                                 $scope.widgetsView[i].widgetText = widgetsReturned[i].name;
221                                 
222                                 if(widgetsReturned[i].headerName.toLowerCase() === 'news'){
223                                         $scope.widgetsView[i].widgetIdentifier = 'NEWS';
224                                 }
225                                 else
226                                 if(widgetsReturned[i].headerName.toLowerCase() === 'resources'){
227                                         $scope.widgetsView[i].widgetIdentifier = 'IMPORTANTRESOURCES';
228                                 }
229                                 else
230                                 if(widgetsReturned[i].headerName.toLowerCase() === 'events'){
231                                         $scope.widgetsView[i].widgetIdentifier = 'EVENTS';
232                                 }
233
234                                 $scope.widgetsView[i].url = widgetsReturned[i].url;
235                                 $scope.widgetsView[i].attrb = widgetsReturned[i].attrs;
236                                 if(widgetsReturned[i].width === null){
237                                         $scope.widgetsView[i].sizeX = 2;
238                                 }else{
239                                         $scope.widgetsView[i].sizeX = widgetsReturned[i].width;
240                                 }
241                                 if(widgetsReturned[i].height === null){
242                                         $scope.widgetsView[i].sizeY = 2;
243                                 }else{
244                                         $scope.widgetsView[i].sizeY = widgetsReturned[i].height;
245                                 }
246                                 $scope.widgetsView[i].row = widgetsReturned[i].x;
247                                 $scope.widgetsView[i].col = widgetsReturned[i].y;
248                         }
249                 if ($scope.widgetsView != undefined
250                                 && $scope.widgetsView != null
251                                 && $scope.widgetsView.length > 0) {
252                         $scope.widgetsViewData = $scope.widgetsView;
253                 }
254                 }
255
256         applicationsService
257         .getUserAppsSortTypePreference().then(function(res) {
258                         var resJson = {};
259                     resJson.value = res;
260                         if (resJson.value==="N" || resJson.value==="") {
261                                 resJson.index = 0;
262                                 resJson.title = 'Name';
263                         }else if (resJson.value==="L") {
264                                 resJson.index = 1;
265                                 resJson.title = 'Last used';
266                         }else if(resJson.value==="F"){
267                                 resJson.index = 2;
268                                 resJson.title = 'Most used';
269                         }else {
270                                 resJson.index = 3;
271                                 resJson.title = 'Manual';
272                         }       
273                         $scope.selectedSortType = resJson;
274                         $scope.selectedSortTypeChanged(res);
275
276                 
277                 });
278                 
279         $scope.widgetsList = [];
280         
281         let getUserWidgets = (loginName) => {
282          var conf = this.conf;
283                  widgetsCatalogService.getUserWidgets(loginName).then(res => {
284                          if(!(res instanceof Array)){
285                                  this.isCommError = true;
286                                  return;
287                          }
288                          for(var i = 0; i < res.length; i++){    
289                                  var widget_id = res[i][0];
290                                  var widget_name = res[i][1];
291                                  let url = this.conf.api.widgetCommon + "/" + widget_id + "/framework.js";
292                                  var header_name = widget_name;
293                                  if(res[i][7] == 1){
294                                         header_name = (widget_name.length > 9) ?widget_name.substring(0, 8) + '...' : widget_name;
295                                  }
296                                  if(res[i][4] === "S" || res[i][4] === null ){
297                                  $scope.widgetsList.push({
298                                            id: widget_id,
299                                            headerName: header_name,
300                                    name: widget_name,
301                                    url: url,
302                                    attrs: [{attr: 'data-' + res[i][0], value: ''}],
303                                    x: res[i][3], 
304                                    y: res[i][5],
305                                    height: res[i][6],
306                                    width: res[i][7]
307                                  });
308                                  }
309                                  var script = document
310                                          .createElement('script');
311                                          script.src = url;
312                                          script.async = false;
313                                          var entry = document
314                                                 .getElementsByTagName('script')[0];
315                                          entry.parentNode
316                                                 .insertBefore(script, entry);
317                          } 
318                 $scope.applyPresentationDetailsToWidgets($scope.widgetsList);
319         }).catch(err => {
320             $log.error('WidgetsHomeCtrl::getUserWidgets error: ' + err);
321         }).finally(()=> {
322          
323         });
324    };
325
326       userProfileService.getUserProfile().then(
327                         function(profile) {
328                                 $scope.orgUserId = profile.orgUserId;
329                                 getUserWidgets($scope.orgUserId);
330           });
331                 
332                 /* Widget Gridster Section */
333                 $scope.newsGridsterItem = {
334                         sizeX : 1,
335                         sizeY : 1,
336                         headerText : 'News',
337                         subHeaderText : '',
338                         imageLink : '',
339                         order : '',
340                         url : ''
341                 };
342
343                 $scope.eventsGridsterItem = {
344                         sizeX : 1,
345                         sizeY : 1,
346                         headerText : 'Events',
347                         subHeaderText : '',
348                         imageLink : '',
349                         order : '',
350                         url : ''
351                 };
352
353                 $scope.impoResGridsterItem = {
354                         sizeX : 1,
355                         sizeY : 1,
356                         headerText : 'Resources',
357                         subHeaderText : '',
358                         imageLink : '',
359                         order : '',
360                         url : ''
361                 };
362                 
363                 this.gridsterAppOpts = {
364                                 columns : 6,
365                                 colWidth : 190,
366                                 rowHeight : 190,
367                                 margins : [ 20, 20 ],
368                                 outerMargin : true,
369                                 pushing : true,
370                                 floating : true,
371                                 swapping : true,
372                                 resizable: {
373                                         enabled: false,
374                                 },
375                                 draggable : {
376                                         handle:'.icon-content-gridguide',
377                                         stop: function stop() { 
378                                                 $scope.defaultSortBy = function() {
379                                                         var resJson = {};
380                                                         resJson.value = 'M';
381                                                         resJson.index = 3;
382                                                         resJson.title = 'Manual';
383                                                         $scope.selectedSortType = resJson;
384                                                         applicationsService.saveAppsSortTypeManual($scope.appsViewData) 
385                                                         applicationsService.saveAppsSortTypePreference($scope.selectedSortType)
386                                                 }
387                                                 $scope.defaultSortBy();                 
388                                         }
389                                 }
390                         };
391                         
392                         this.gridsterWidgetOpts = {
393                                         columns : 6,
394                                         colWidth : 190,
395                                         rowHeight : 190,
396                                         margins : [ 20, 20 ],
397                                         outerMargin : true,
398                                         pushing : true,
399                                         floating : true,
400                                         swapping : true,
401                                         resizable: {
402                                                 enabled: true,
403                                                 stop: function stop(event, uiWidget, $element){
404                                                         if($element.sizeX == 1)
405                                                                 $element.headerText = ($element.widgetText.length > 9) ? $element.widgetText.substring(0, 8) + '...' : $element.widgetText;
406                                                         if($element.sizeX >= 2)
407                                                                 $element.headerText = $element.widgetText;
408                                                         
409                                                         applicationsService
410                                                         .saveWidgetsSortManual($scope.widgetsViewData)
411                                         
412                                                 }
413                                         },
414                                         draggable : {
415                                                 handle:'.icon-content-gridguide',
416                                                 stop: function stop(){
417                                                         applicationsService
418                                                         .saveWidgetsSortManual($scope.widgetsViewData)
419                                         
420                                                 }
421                                         }
422                         };
423                 
424                 this.goToCatalog = function(item) {
425                         $state.go('root.appCatalog');
426                 } 
427                 
428                 this.goToWidgetCatLog = function(item) {
429                         $state.go('root.widgetCatalog');
430                 } 
431                 
432                 // navigate to application url in new tab
433                 this.goToPortal = function(item) {
434                         userProfileService.getUserRolesForApplication($scope.orgUserId,item.appid)
435                   .then(res=>{
436                           var count = 0;
437                           for(var i=0;i<res.length;i++){
438                                  if(!res[i].isApplied)
439                                          {
440                                          count++;
441                                          }
442                                    }
443                           if((count>0 && res.length == count)||res.length==0)
444                                   {
445                                 confirmBoxService.showInformation('You have no roles assigned to this application to access.').then(isConfirmed => {});
446
447                                   }
448                           else{
449                                         if (!item.url) {
450                                                 $log.error('No URL found for this application, doing nothing!');
451                                                 return;
452                                         }
453                                         if (item.restrictedApp) {
454                                                 // Link-based apps open in their own browser tab
455                                                 $window.open(item.url, '_blank');
456                                         } else {
457                                                 // cache control so browsers load app page every time
458                                                 var ccParam = 'cc=' + new Date().getTime();
459                                                 var urlParts = item.url.split('#');
460                                                 var appUrl = null;
461                                                 if (urlParts.length < 2) {
462                                                         // no #
463                                                         let urlLastChar = item.url.charAt(item.url.length - 1);
464                                                         if (item.url.includes("?"))
465                                                                 appUrl = (urlLastChar === '&' ? item.url + ccParam : item.url + '&' + ccParam);
466                                                         else 
467                                                                 appUrl = item.url + '?' + ccParam;
468                                                 } else {
469                                                         // has #
470                                                         let urlLastChar = urlParts[0].charAt(urlParts[0].length - 1);
471                                                         if (item.url.includes("?"))
472                                                                 appUrl = (urlLastChar === '&' ? urlParts[0] + ccParam + '#' + urlParts[1]  :  urlParts[0] + '&' + ccParam + '#' + urlParts[1]);
473                                                         else
474                                                                 appUrl = urlParts[0] + '?' + ccParam + "#" + urlParts[1];
475                                                 }
476                                                 // $log.debug('DashboardCtrlr::goToPortal: opening tab with URL
477                                                 // ' + appUrl);
478                                                 var tabContent = {
479                                                         id: new Date(),
480                                                         title: item.headerText,
481                                                         url: appUrl,
482                                                         appId: item.appId
483                                                 };
484                                                 $cookies.putObject('addTab', tabContent);
485                                         }
486                                   
487                           }
488                  });
489                 
490                         
491                 
492
493                 };
494                 
495                 this.auditLog = function(app) {
496                         console.log(app);
497                         auditLogService.storeAudit(app.appid,'app',app.url);
498                 };
499                 
500                 if (getParameterByName('noUserError') != null) {
501                         if (getParameterByName('noUserError') == "Show") {
502                                 $("#errorInfo").show();
503                         }
504                 }               
505         };
506
507         DashboardCtrl.$inject = [ 'conf', 'applicationsService', '$log', '$window',
508                         'userProfileService', '$scope', '$cookies', '$timeout', '$interval', 
509                         '$modal',  '$state', 'beReaderService', 'dashboardService', 'confirmBoxService', 
510                         'auditLogService', 'ngDialog', '$compile', 'widgetsCatalogService' ];
511         angular.module('ecompApp').controller('DashboardCtrl', DashboardCtrl);
512 })();
513
514 function getParameterByName(name, url) {
515         if (!url)
516                 url = window.location.href;
517         name = name.replace(/[\[\]]/g, "\\$&");
518         var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex
519                         .exec(url);
520         if (!results)
521                 return '';
522         if (!results[2])
523                 return '';
524         return results[2].replace(/\+/g, " ");
525 }