MariaDB Connector and Sonar Scans; clean nl
[portal.git] / ecomp-portal-FE-os / client / src / views / applications / application-details-dialog / application-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 'use strict';
21 (function () {
22     class AppDetailsModalCtrl {
23         constructor($scope, $log, applicationsService, errorMessageByCode,
24                     ECOMP_URL_REGEX,userProfileService, $cookies, confirmBoxService,items) {
25 //            let emptyImg = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
26             // empty image should really be empty, or it causes problems for the back end
27             let emptyImg = null;
28             this.emptyImgForPreview = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
29             $scope.ngDialogData=items;
30             let newAppModel = {
31                 'id': null,
32                 'name': null,
33                 'imageUrl': null,
34                 'description': null,
35                 'notes': null,
36                 'url': null,
37                 'alternateUrl': null,
38                 'restUrl': null,
39                 'isOpen': false,
40                 'username': null,
41                 'appPassword': null,
42                 'thumbnail': emptyImg,
43                 'isEnabled': true,
44                 'restrictedApp': false,
45                 'nameSpace': null,
46                 'isCentralAuth': false                
47             };
48
49             let init = () => {
50                 $log.info('AppDetailsModalCtrl::init');
51                 this.isSaving = false;
52                 if($scope.ngDialogData && $scope.ngDialogData.app){
53                     $log.debug('AppDetailsModalCtrl:init:: Edit app mode for', $scope.ngDialogData.app);
54                     this.isEditMode = true;
55                     this.app = _.clone($scope.ngDialogData.app);
56                 }else{
57                     $log.debug('AppDetailsModalCtrl:init:: New app mode');
58                     this.isEditMode = false;
59                     this.app = _.clone(newAppModel);
60                 }
61                 this.originalImage = null
62             };
63
64             this.ECOMP_URL_REGEX = ECOMP_URL_REGEX;
65
66             this.imageApi = {};
67             this.removeImage = () => {
68                 $log.debug('AppDetailsModalCtrl:removeImage:: entering removeImage');
69
70                 confirmBoxService.confirm("Are you sure you want to remove the image?").then(isConfirmed => {
71                     if(isConfirmed){
72                         this.imageApi.clearFile();
73                         this.app.thumbnail = emptyImg;
74                         this.originalImage = null;
75                         this.app.imageUrl = null;
76                         this.app.imageLink = null;
77                     }
78                 }).catch(err => {
79                     $log.error('AppDetailsModalCtrl:removeImage error:: ',err);
80                 });
81             };
82
83             //This part handles conflict errors (409)
84             this.conflictMessages = {};
85             this.scrollApi = {};
86             let handleConflictErrors = err => {
87                 if(!err.data){
88                     return;
89                 }
90                 if(!err.data.length){ //support objects
91                     err.data = [err.data]
92                 }
93                 _.forEach(err.data, item => {
94                     _.forEach(item.fields, field => {
95                         //set conflict message
96                         this.conflictMessages[field.name] = errorMessageByCode[item.errorCode];
97                         //set field as invalid
98                         $scope.appForm[field.name].$setValidity('conflict', false);
99                         //set watch once to clear error after user correction
100                         watchOnce[field.name]();
101                     });
102                 });
103                 this.scrollApi.scrollTop();
104             };
105
106             let resetConflict = fieldName => {
107                 delete this.conflictMessages[fieldName];
108                 if($scope.appForm[fieldName]){
109                     $scope.appForm[fieldName].$setValidity('conflict', true);
110                 }
111             };
112
113
114             let emptyCookies = () => {
115                 $log.debug('AppDetailsModalCtrl:emptyCookies:: entering emptyCookies');
116                 userProfileService.getUserProfile()
117                     .then(profile=> {
118                         // $log.info(profile);
119                         $scope.orgUserId = profile.orgUserId;
120                         $log.debug('AppDetailsModalCtrl:emptyCookies for the following orgUserId: ' + profile.orgUserId);
121                         if ($cookies.getObject($scope.orgUserId + '_apps') != undefined && $cookies.getObject($scope.orgUserId + '_apps') != null) {
122                             $cookies.remove($scope.orgUserId + '_apps');
123                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_apps');
124                         }
125                         if ($cookies.getObject($scope.orgUserId + '_widget') != undefined && $cookies.getObject($scope.orgUserId + '_widget') != null) {
126                             $cookies.remove($scope.orgUserId + '_widget');
127                             $log.debug('AppDetailsModalCtrl:emptyCookies removed: ' + $scope.orgUserId + '_widget');
128                         }
129                     }).catch(err => {
130                         $log.error('AppDetailsModalCtrl:emptyCookies error:: '+ JSON.stringify(err));
131                     });
132             };
133
134
135             let watchOnce = {
136                 name: () => {
137                     let unregisterName = $scope.$watch('appDetails.app.name', (newVal, oldVal) => {
138                         // $log.debug('newVal, oldVal = ' + newVal.toLowerCase() + " | " + oldVal.toLowerCase())
139                         if(newVal.toLowerCase() !== oldVal.toLowerCase()){
140                             resetConflict('name');
141                             unregisterName();
142                         }
143                     });
144                 },
145                 url: () => {
146                     let unregisterUrl = $scope.$watch('appDetails.app.url', (newVal, oldVal) => {
147                         if(newVal.toLowerCase() !== oldVal.toLowerCase()) {
148                             resetConflict('url');
149                             unregisterUrl();
150                         }
151                     });
152                 }
153             };
154             //***************************
155
156             this.saveChanges = () => {
157                 //if valid..
158                  if(((angular.isUndefined(this.app.name) || !this.app.name)&&(angular.isUndefined(this.app.url) || !this.app.url)
159                                  &&(angular.isUndefined(this.app.username) || !this.app.username)&&(angular.isUndefined(this.app.appPassword) || !this.app.appPassword))) {
160                          confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
161                      return;
162                  }else if(!((angular.isUndefined(this.app.name) || !!this.app.name)&&(angular.isUndefined(this.app.url) || !!this.app.url))){
163                      confirmBoxService.showInformation('Please fill in all required fields').then(isConfirmed => {});
164                      return;
165                  }
166                 this.isSaving = true;
167                 // For a restricted app, null out all irrelevant fields
168                 if (this.app.restrictedApp) {
169                     this.app.restUrl = null;
170                     this.app.isOpen = true;
171                     this.app.username = null;
172                     this.app.appPassword = null;
173                     this.app.uebTopicName = null;
174                     this.app.uebKey = null;
175                     this.app.uebSecret = null;
176                 }
177                 if(this.isEditMode){
178                     if (this.app.nameSpace=="") {this.app.nameSpace = null;}
179                     applicationsService.updateOnboardingApp(this.app)
180                         .then(() => {
181                             $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: App update succeeded!');
182                           //  $scope.closeThisDialog(true);
183                             $scope.$dismiss('cancel');
184                             emptyCookies();
185                         }).catch(err => {
186                             switch (err.status) {
187                                 case '409':         // Conflict
188                                     handleConflictErrors(err);
189                                     break;
190                                 case '500':         // Internal Server Error
191                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
192                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
193                                     break;
194                                 case '403':         // Forbidden... possible webjunction error to try again
195                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
196                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
197                                     break;
198                                 default:
199                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
200                                         'Please try again. If the problem persists, then try again later. Error: ' + err.status).then(isConfirmed => {});
201                             }
202                             $log.error('applicationsService:updateOnboardingApp error:: '+ JSON.stringify(err));
203                         }).finally(()=>{
204                             this.isSaving = false;
205                             // for bug in IE 11
206                             var objOffsetVersion = objAgent.indexOf("MSIE");
207                             if (objOffsetVersion != -1) {
208                                 $log.debug('AppDetailsModalCtrl:updateOnboardingApp:: Browser is IE, forcing Refresh');
209                                 $window.location.reload();            // for bug in IE 11
210                             }
211                             // for bug in IE 11
212                         });
213                 }else{
214                     applicationsService.addOnboardingApp(this.app)
215                         .then(() => {
216                             $log.debug('App creation succeeded!');
217                             //$scope.closeThisDialog(true);
218                             $scope.$dismiss('cancel');
219                             emptyCookies();
220                         }).catch(err => {
221                             switch (err.status) {
222                                 case '409':         // Conflict
223                                     handleConflictErrors(err);
224                                     break;
225                                 case '500':         // Internal Server Error
226                                     confirmBoxService.showInformation('There was a problem adding the application information. ' +
227                                         'Please try again later. Error: ' + err.status).then(isConfirmed => {});
228                                     break;
229                                 default:
230                                     confirmBoxService.showInformation('There was a problem updating the application changes. ' +
231                                         'Please try again. If the problem persists, then try again later. Error: ' +
232                                         err.status).then(isConfirmed => {});
233                             }
234                             $log.error('applicationsService:addOnboardingApp error:: '+ JSON.stringify(err));
235                         }).finally(()=>{
236                             this.isSaving = false;
237                             // for bug in IE 11
238                             var objOffsetVersion = objAgent.indexOf("MSIE");
239                             if (objOffsetVersion != -1) {
240                                 $log.debug('applicationsService:addOnboardingApp:: Browser is IE, forcing Refresh');
241                                 $window.location.reload();            // for bug in IE 11
242                             }
243                             // for bug in IE 11
244                         });
245                 }
246                 
247             };
248
249
250             init();
251
252             $scope.$watch('appDetails.originalImage', (newVal, oldVal) => {
253               if((!newVal || !newVal.resized) && !this.app.imageUrl){
254                   if (!newVal) {
255                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is null');
256                   } else {
257                       $log.debug('applicationsService:$scope.$watch:: originalImage: newVal is not resized and no imageUrl');
258                   }
259                   this.app.imageUrl = null;
260                   this.app.thumbnail = emptyImg;
261                   return;
262               }
263
264                 if(!(_.isEqual(newVal, oldVal))){
265                     $log.debug('applicationsService:$scope.$watch:: thumbnail updated!');
266                     this.app.imageUrl = null;
267                     this.app.imageLink = null;
268                     this.app.thumbnail = newVal.resized.dataURL;
269                 }
270             });
271
272             $scope.$on('$stateChangeStart', e => {
273                 //Disable navigation when modal is opened
274                 e.preventDefault();
275             });
276         }
277     }
278     AppDetailsModalCtrl.$inject = ['$scope', '$log', 'applicationsService', 'errorMessageByCode',
279         'ECOMP_URL_REGEX','userProfileService','$cookies', 'confirmBoxService','items'];
280     angular.module('ecompApp').controller('AppDetailsModalCtrl', AppDetailsModalCtrl);
281 })();