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