[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-FE-common / client / app / views / widgets / widget-details-dialog / widget-details.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 /**
21  * Created by nnaffar on 12/20/15.
22  */
23 'use strict';
24 (function () {
25     class WidgetDetailsModalCtrl {
26         constructor($scope, $log, applicationsService, widgetsService, errorMessageByCode,
27                     ECOMP_URL_REGEX, $window, userProfileService, $cookies, $rootScope) {
28
29             let newWidgetModel = {
30                 name: null,
31                 appId: null,
32                 appName: null,
33                 width: 360,
34                 height: 300,
35                 url: null
36             };
37
38             let getAvailableApps = () => {
39                 applicationsService.getAppsForSuperAdminAndAccountAdmin().then(apps => {
40                     this.availableApps=[];
41                     for(var i=0;i<apps.length;i++) {
42                         if (!apps[i].restrictedApp) {
43                             $log.debug('WidgetDetailsModalCtrl::getAvailableApps: pushing {id: ', apps[i].id, 'name: ', apps[i].name,
44                                             'restrictedApp: ', apps[i].restrictedApp, '}');
45                             this.availableApps.push({
46                                 id: apps[i].id,
47                                 name: apps[i].name,
48                                 restrictedApp: apps[i].restrictedApp
49                             });
50                         }
51                     }
52                     
53                     if (this.isEditMode) {
54                         this.selectedApp = _.find(apps, {id: this.widget.appId});
55                         if(!this.selectedApp){
56                             //workaround to display validation errors for apps dropdown in case selectedApp isn't valid
57                             $scope.widgetForm.app.$dirty = true;
58                         }
59                     } else {
60                         this.selectedApp = null;
61                     }
62                     //init appId & appName with selectedApp
63                     this.updateSelectedApp();
64                 }).catch(err => {
65                     confirmBoxService.showInformation('There was a problem retrieving the Widgets. ' +
66                         'Please try again later.').then(isConfirmed => {});
67                     $log.error('WidgetDetailsModalCtrl::getAvailableApps error: '+ err);
68                 });
69             };
70             /**/
71
72             let init = () => {
73                 this.isSaving = false;
74                 if ($scope.ngDialogData && $scope.ngDialogData.widget) {
75                     $log.debug('WidgetDetailsModalCtrl::getAvailableApps: Edit widget mode for', $scope.ngDialogData.widget);
76                     this.isEditMode = true;
77                     this.widget = _.clone($scope.ngDialogData.widget);
78                 } else {
79                     $log.debug('WidgetDetailsModalCtrl::init: New app mode');
80                     this.isEditMode = false;
81                     this.widget = _.clone(newWidgetModel);
82                 }
83                 getAvailableApps();
84             };
85
86             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
87
88             //This part handles conflict errors (409)
89             this.conflictMessages = {};
90             this.scrollApi = {};
91             let handleConflictErrors = err => {
92                 if(!err.data){
93                     return;
94                 }
95                 if(!err.data.length){ //support objects
96                     err.data = [err.data]
97                 }
98                 _.forEach(err.data, item => {
99                     _.forEach(item.fields, field => {
100                         //set conflict message
101                         this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
102                         //set field as invalid
103                         $scope.widgetForm[field.name].$setValidity('conflict', false);
104                         //set watch once to clear error after user correction
105                         watchOnce[field.name]();
106                     });
107                 });
108                 this.scrollApi.scrollTop();
109             };
110
111             let resetConflict = fieldName => {
112                 delete this.conflictMessages[fieldName];
113                 if($scope.widgetForm[fieldName]){
114                     $scope.widgetForm[fieldName].$setValidity('conflict', true);
115                 }
116             };
117
118             let watchOnce = {
119                 name: () => {
120                     let unregisterName = $scope.$watchGroup(['widgetDetails.selectedApp','widgetDetails.widget.name'], (newVal, oldVal) => {
121                         if(newVal.toLowerCase() !== oldVal.toLowerCase()){
122                             resetConflict('name');
123                             unregisterName();
124                         }
125                     });
126                 },
127                 url: () => {
128                     let unregisterUrl = $scope.$watch('widgetDetails.widget.url', (newVal, oldVal) => {
129                         if(newVal.toLowerCase() !== oldVal.toLowerCase()) {
130                             resetConflict('url');
131                             unregisterUrl();
132                         }
133                     });
134                 }
135             };
136             //***************************
137
138             this.updateSelectedApp = () => {
139                 if (!this.selectedApp) {
140                     return;
141                 }
142                 this.widget.appId = this.selectedApp.id;
143                 this.widget.appName = this.selectedApp.name;
144             };
145
146             let emptyCookies = () => {
147                 userProfileService.getUserProfile()
148                     .then(profile=> {
149                         $scope.orgUserId = profile.orgUserId;
150                         if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
151                             $cookies.remove($scope.orgUserId + '_widget');
152                         }
153                     }).catch(err => {
154                         $log.error('WidgetDetailsModalCtrl::emptyCookies: There was a problem emptying the cookies! No user error presented though.');
155                     });
156             };
157
158             this.saveChanges = () => {
159                 if($scope.widgetForm.$invalid){
160                     return;
161                 }
162                 this.isSaving = true;
163                 if(this.isEditMode){
164                     widgetsService.updateWidget(this.widget.id, this.widget)
165                         .then(() => {
166                             $log.debug('WidgetDetailsModalCtrl::saveChanges: Widget update succeeded!');
167                             $scope.closeThisDialog(true);
168                             emptyCookies();
169                         }).catch(err => {
170                             if(err.status === 409){//Conflict
171                                 handleConflictErrors(err);
172                             } else {
173                                 confirmBoxService.showInformation('There was a problem saving the Widget. ' +
174                                     'Please try again later. Error Status: ' + err.status).then(isConfirmed => {});
175                             }
176                             $log.error('WidgetDetailsModalCtrl::saveChanges error: ', err);
177                         }).finally(()=>{
178                             this.isSaving = false;
179                             // for bug in IE 11
180                             var objOffsetVersion = objAgent.indexOf("MSIE");
181                             if (objOffsetVersion != -1) {
182                                 $log.debug('WidgetDetailsModalCtrl::saveChanges: Browser is IE, forcing Refresh');
183                                 $window.location.reload();            // for bug in IE 11
184                             }
185                             // for bug in IE 11
186                         });
187                 } else {
188                     widgetsService.createWidget(this.widget)
189                         .then(() => {
190                             $log.debug('WidgetDetailsModalCtrl::createWidget: Widget creation succeeded!');
191                             $scope.closeThisDialog(true);
192                             emptyCookies();
193                             $rootScope.noWidgets = false;
194                         }).catch(err => {
195                         if(err.status === 409){//Conflict
196                             handleConflictErrors(err);
197                         } else {
198                             confirmBoxService.showInformation('There was a problem creating the Widget. ' +
199                                 'Please try again later. Error Status: ' + err.status).then(isConfirmed => {});
200                         }
201                         $log.error('WidgetDetailsModalCtrl::createWidget error: ',err);
202                     }).finally(()=>{
203                         this.isSaving = false;
204                         // for bug in IE 11
205                         var objOffsetVersion = objAgent.indexOf("MSIE");
206                         if (objOffsetVersion != -1) {
207                             $log.debug('WidgetDetailsModalCtrl::createWidget: Browser is IE, forcing Refresh');
208                             $window.location.reload();            // for bug in IE 11
209                         }
210                         // for bug in IE 11
211                     });
212                 }
213             };
214
215             init();
216
217             $scope.$on('$stateChangeStart', e => {
218                 //Disable navigation when modal is opened
219                 e.preventDefault();
220             });
221         }
222     }
223     WidgetDetailsModalCtrl.$inject = ['$scope', '$log', 'applicationsService', 'widgetsService', 'errorMessageByCode',
224         'ECOMP_URL_REGEX', '$window','userProfileService','$cookies', '$rootScope'];
225     angular.module('ecompApp').controller('WidgetDetailsModalCtrl', WidgetDetailsModalCtrl);
226 })();