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