Catalog alignment
[sdc.git] / catalog-ui / src / app / view-models / workspace / workspace-view-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 /**
22  * Created by obarda on 3/30/2016.
23  */
24 'use strict';
25 import * as _ from 'lodash';
26 import {
27     IUserProperties,
28     IAppMenu,
29     Resource,
30     Component,
31     Plugin,
32     PluginsConfiguration,
33     PluginDisplayOptions
34 } from 'app/models';
35 import {
36     MenuItem, ModalsHandler, States, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ResourceType, PREVIOUS_CSAR_COMPONENT,
37     WorkspaceMode, ComponentFactory, ChangeLifecycleStateHandler, Role, ComponentState, MenuItemGroup, MenuHandler
38 } from 'app/utils';
39 import {
40     EventListenerService,
41     LeftPaletteLoaderService,
42     ProgressService
43 } from 'app/services';
44 import {
45     CacheService
46 } from 'app/services-ng2';
47 import { AutomatedUpgradeService } from '../../ng2/pages/automated-upgrade/automated-upgrade.service';
48 import { CatalogService } from '../../ng2/services/catalog.service';
49 import { ComponentServiceNg2 } from '../../ng2/services/component-services/component.service';
50 import { EventBusService } from '../../ng2/services/event-bus.service';
51 import { HomeService } from '../../ng2/services/home.service';
52 import { PluginsService } from '../../ng2/services/plugins.service';
53 import { IDependenciesServerResponse } from '../../ng2/services/responses/dependencies-server-response';
54 import { WorkspaceNg1BridgeService } from '../../ng2/pages/workspace/workspace-ng1-bridge-service';
55 import { WorkspaceService } from '../../ng2/pages/workspace/workspace.service';
56
57
58 export interface IWorkspaceViewModelScope extends ng.IScope {
59
60     isLoading: boolean;
61     isCreateProgress: boolean;
62     component: Component;
63     originComponent: Component;
64     componentType: string;
65     importFile: any;
66     leftBarTabs: MenuItemGroup;
67     isNew: boolean;
68     isFromImport: boolean;
69     isValidForm: boolean;
70     isActiveTopBar: boolean;
71     mode: WorkspaceMode;
72     breadcrumbsModel: Array<MenuItemGroup>;
73     sdcMenu: IAppMenu;
74     changeLifecycleStateButtons: any;
75     version: string;
76     versionsList: Array<any>;
77     changeVersion: any;
78     isComposition: boolean;
79     isDeployment: boolean;
80     isPlugins: boolean;
81     $state: ng.ui.IStateService;
82     user: IUserProperties;
83     thirdParty: boolean;
84     disabledButtons: boolean;
85     menuComponentTitle: string;
86     progressService: ProgressService;
87     progressMessage: string;
88     ComponentServiceNg2: ComponentServiceNg2;
89     // leftPanelComponents:Array<Models.Components.Component>; //this is in order to load the left panel once, and not wait long time when moving to composition
90     unsavedChanges: boolean;
91     unsavedChangesCallback: Function;
92     unsavedFile: boolean;
93     hasNoDependencies: boolean;
94
95
96     startProgress(message: string): void;
97     stopProgress(): void;
98     updateBreadcrumbs(component: Component): void;
99     updateUnsavedFileFlag(isUnsaved: boolean): void;
100     showChangeStateButton(): boolean;
101     getComponent(): Component;
102     setComponent(component: Component): void;
103     setOriginComponent(component: Component): void;
104     onMenuItemPressed(state: string, params: any): ng.IPromise<boolean>;
105     create(): void;
106     save(): Promise<void>;
107     setValidState(isValid: boolean): void;
108     changeLifecycleState(state: string): void;
109     handleChangeLifecycleState(state: string, newCsarVersion?: string, errorFunction?: Function): void;
110     disableMenuItems(): void;
111     enableMenuItems(): void;
112     isDesigner(): boolean;
113     isViewMode(): boolean;
114     isEditMode(): boolean;
115     isCreateMode(): boolean;
116     isDisableMode(): boolean;
117     isGeneralView(): boolean;
118     goToBreadcrumbHome(): void;
119     onVersionChanged(selectedId: string): void;
120     getLatestVersion(): void;
121     getStatus(): string;
122     showLifecycleIcon(): boolean;
123     updateSelectedMenuItem(state: string): void;
124     isSelected(menuItem: MenuItem): boolean;
125     uploadFileChangedInGeneralTab(): void;
126     updateMenuComponentName(ComponentName: string): void;
127     getTabTitle(): string;
128     reload(component: Component): void;
129 }
130
131 export class WorkspaceViewModel {
132
133     static '$inject' = [
134         '$scope',
135         'injectComponent',
136         'ComponentFactory',
137         '$state',
138         'sdcMenu',
139         '$q',
140         'MenuHandler',
141         'Sdc.Services.CacheService',
142         'ChangeLifecycleStateHandler',
143         'LeftPaletteLoaderService',
144         '$filter',
145         'EventListenerService',
146         'Notification',
147         '$stateParams',
148         'HomeService',
149         'CatalogService',
150         'Sdc.Services.ProgressService',
151         'ComponentServiceNg2',
152         'AutomatedUpgradeService',
153         'EventBusService',
154         'PluginsService',
155         'WorkspaceNg1BridgeService',
156         'workspaceService'
157     ];
158
159     constructor(private $scope: IWorkspaceViewModelScope,
160                 private injectComponent: Component,
161                 private ComponentFactory: ComponentFactory,
162                 private $state: ng.ui.IStateService,
163                 private sdcMenu: IAppMenu,
164                 private $q: ng.IQService,
165                 private MenuHandler: MenuHandler,
166                 private cacheService: CacheService,
167                 private ChangeLifecycleStateHandler: ChangeLifecycleStateHandler,
168                 private LeftPaletteLoaderService: LeftPaletteLoaderService,
169                 private $filter: ng.IFilterService,
170                 private EventListenerService: EventListenerService,
171                 private Notification: any,
172                 private $stateParams: any,
173                 private homeService: HomeService,
174                 private catalogService: CatalogService,
175                 private progressService: ProgressService,
176                 private ComponentServiceNg2: ComponentServiceNg2,
177                 private AutomatedUpgradeService: AutomatedUpgradeService,
178                 private eventBusService: EventBusService,
179                 private pluginsService: PluginsService,
180                 private workspaceNg1BridgeService: WorkspaceNg1BridgeService,
181                 private workspaceService: WorkspaceService) {
182
183                 this.initScope();
184                 // this.initAfterScope();
185                 this.$scope.updateSelectedMenuItem(this.$state.current.name);
186     }
187
188     private role: string;
189     private category: string;
190     private components: Component[];
191     
192     private initViewMode = ():WorkspaceMode => {
193         let mode = WorkspaceMode.VIEW;
194
195         if (!this.$state.params['id']) {   //&& !this.$state.params['vspComponent']
196             mode = WorkspaceMode.CREATE;
197         } else {
198             if (this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT &&
199                 this.$scope.component.lastUpdaterUserId === this.cacheService.get('user').userId) {
200                 if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role === Role.DESIGNER) {
201                     mode = WorkspaceMode.EDIT;
202                 }
203             }
204         }
205         this.workspaceNg1BridgeService.updateIsViewOnly(mode === WorkspaceMode.VIEW);
206         return mode;
207     }
208
209     private initChangeLifecycleStateButtons = (): void => {
210         let state: string;
211         if (this.$scope.component.isService() && this.$scope.component.lifecycleState === 'CERTIFIED') {
212             state = this.$scope.component.distributionStatus;
213         } else {
214             state = this.$scope.component.lifecycleState;
215         }
216         this.$scope.changeLifecycleStateButtons = (this.sdcMenu.roles[this.role].changeLifecycleStateButtons[state] || [])[this.$scope.component.componentType.toUpperCase()];
217     }
218
219     private initScope = (): void => {
220         this.$scope.component = this.injectComponent;
221         this.$scope.menuComponentTitle = this.$scope.component.name;
222         this.$scope.disabledButtons = false;
223         this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component);
224         this.$scope.componentType = this.$scope.component.componentType;
225         this.$scope.version = this.cacheService.get('version');
226         this.$scope.user = this.cacheService.get('user');
227         this.role = this.$scope.user.role;
228         this.category = this.$scope.component.selectedCategory;
229         this.$scope.mode = this.initViewMode();
230         this.$scope.isValidForm = true;
231         this.initChangeLifecycleStateButtons();
232         this.initVersionObject();
233         this.$scope.$state = this.$state;
234         this.$scope.isLoading = false;
235         this.$scope.isComposition = (this.$state.current.name.indexOf(States.WORKSPACE_COMPOSITION) > -1);
236         this.$scope.isDeployment = this.$state.current.name == States.WORKSPACE_DEPLOYMENT;
237         this.$scope.progressService = this.progressService;
238         this.$scope.unsavedChanges = false;
239
240         this.$scope.hasNoDependencies = true;
241         this.verifyIfDependenciesExist();
242
243         this.EventListenerService.registerObserverCallback(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES, this.setWorkspaceButtonState);
244         this.$scope.getComponent = (): Component => {
245             return this.$scope.component;
246         };
247
248         this.$scope.updateMenuComponentName = (ComponentName:string):void => {
249             this.$scope.menuComponentTitle = ComponentName;
250         };
251
252         this.$scope.sdcMenu = this.sdcMenu;
253         // Will be called from each step after save to update the resource.
254         this.$scope.setComponent = (component:Component):void => {
255             this.$scope.component = component;
256         };
257
258         this.$scope.setOriginComponent = (component:Component):void => {
259             this.$scope.originComponent = component;
260         }
261
262         this.$scope.uploadFileChangedInGeneralTab = ():void => {
263             // In case user select browse file, and in update mode, need to disable submit for testing and checkin buttons.
264             if (this.$scope.isEditMode() && this.$scope.component.isResource() && (<Resource>this.$scope.component).resourceType == ResourceType.VF) {
265                 // NOTE: Commented out the disabling of the workspace buttons on CSAR updating due fix of a bug [417534]
266                 // this.$scope.disabledButtons = true;
267             }
268         };
269
270         this.$scope.archiveComponent = ():void => {
271             this.$scope.isLoading = true;
272             const typeComponent = this.$scope.component.componentType;
273             this.ComponentServiceNg2.archiveComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=> {
274                 this.$scope.isLoading = false;
275                 if (this.$state.params.previousState) {
276                     switch (this.$state.params.previousState) {
277                         case 'catalog':
278                         case 'dashboard':
279                             this.$state.go(this.$state.params.previousState);
280                             break;
281                         default:
282                             break;
283                     }
284                 }
285                 this.$scope.component.archived = true;
286                 this.deleteArchiveCache();
287
288                 this.Notification.success({
289                     message: this.$scope.component.name + ' ' + this.$filter('translate')("ARCHIVE_SUCCESS_MESSAGE_TEXT"),
290                     title: this.$filter('translate')("ARCHIVE_SUCCESS_MESSAGE_TITLE")
291                 });
292             }, (error) => { this.$scope.isLoading = false; });
293         }
294
295         this.$scope.restoreComponent = ():void => {
296             this.$scope.isLoading = true;
297             const typeComponent = this.$scope.component.componentType;
298             this.ComponentServiceNg2.restoreComponent(typeComponent, this.$scope.component.uniqueId).subscribe(()=> {
299                 this.$scope.isLoading = false;
300                 this.Notification.success({
301                     message: this.$scope.component.name + ' ' + this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TEXT"),
302                     title: this.$filter('translate')("RESTORE_SUCCESS_MESSAGE_TITLE")
303                 });
304             });
305             this.$scope.component.archived = false;
306             this.deleteArchiveCache();
307         }
308
309         this.$scope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) => {
310             if(this.$scope.isEditMode()){
311                 if (fromParams.id == toParams.id && this.$state.current.data && this.$state.current.data.unsavedChanges) {
312                     event.preventDefault();
313                     if(this.$scope.isValidForm){
314                         this.$scope.save().then(() => {
315                             this.$scope.onMenuItemPressed(toState.name, toParams);
316                         }, ()=> {
317                             console.error("Save failed, unable to navigate to " + toState.name);
318                         })
319                     } else {
320                         console.error("Form is invalid, unable to navigate to " + toState.name);
321                     }
322                 }
323             }
324
325         });
326
327         this.$scope.$on('$stateChangeSuccess', (event, toState) => {
328             this.$scope.updateSelectedMenuItem(this.$state.current.name);
329         });
330
331         this.$scope.onMenuItemPressed = (state:string, params:any):ng.IPromise<boolean> => {
332
333             let deferred:ng.IDeferred<boolean> = this.$q.defer();
334             let goToState = ():void => {
335                 this.$state.go(state, Object.assign({
336                     id: this.$scope.component.uniqueId,
337                     type: this.$scope.component.componentType.toLowerCase(),
338                     components: this.components
339                 }, params));
340                 deferred.resolve(true);
341             };
342
343             if (this.$scope.isEditMode() && //this is a workaround for amdocs - we need to get the artifact in order to avoid saving the vf when moving from their tabs
344                 (this.$state.current.name === States.WORKSPACE_MANAGEMENT_WORKFLOW || this.$state.current.name === States.WORKSPACE_NETWORK_CALL_FLOW)) {
345                 let onGetSuccess = (component:Component) => {
346                     this.$scope.isLoading = false;
347                     // Update the components
348                     this.$scope.component = component;
349                     goToState();
350                 };
351                 let onFailed = () => {
352                     this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
353                     this.$scope.isLoading = false; // stop the progress.
354                     deferred.reject(false);
355                 };
356                 this.$scope.component.getComponent().then(onGetSuccess, onFailed);
357             } else {
358                 goToState();
359             }
360             return deferred.promise;
361         };
362
363         this.$scope.setValidState = (isValid:boolean):void => {
364             this.$scope.isValidForm = isValid;
365         };
366
367         this.$scope.onVersionChanged = (selectedId:string):void => {
368             if (this.$scope.isGeneralView() && this.$state.current.data.unsavedChanges) {
369                 this.$scope.changeVersion.selectedVersion = _.find(this.$scope.versionsList, (versionObj)=> {
370                     return versionObj.versionId === this.$scope.component.uniqueId;
371                 });
372             }
373
374             let eventData = {
375                 uuid: this.$scope.component.uuid,
376                 version: this.$scope.changeVersion.selectedVersion.versionNumber
377             };
378
379             this.eventBusService.notify("VERSION_CHANGED", eventData).subscribe(() => {
380                 this.$scope.isLoading = true;
381
382                 this.$state.go(this.$state.current.name, {
383                     id: selectedId,
384                     type: this.$scope.componentType.toLowerCase(),
385                     mode: WorkspaceMode.VIEW,
386                     components: this.$state.params['components']
387                 }, {reload: true});
388             });
389         };
390
391         this.$scope.getLatestVersion = ():void => {
392             this.$scope.onVersionChanged(_.first(this.$scope.versionsList).versionId);
393         };
394
395         this.$scope.create = () => {
396
397             this.$scope.startProgress("Creating Asset...");
398             _.first(this.$scope.leftBarTabs.menuItems).isDisabled = true;//disabled click on general tab (DE246274)
399
400              // In case we import CSAR. Notify user that import VF will take long time (the create is performed in the background).
401              if (this.$scope.component.isResource() && (<Resource>this.$scope.component).csarUUID) {
402                 this.Notification.info({
403                     message: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_DESCRIPTION"),
404                     title: this.$filter('translate')("IMPORT_VF_MESSAGE_CREATE_TAKES_LONG_TIME_TITLE")
405                 });
406             }
407
408             let onFailed = () => {
409                 this.$scope.stopProgress();
410                 this.$scope.isLoading = false; // stop the progress.
411                 _.first(this.$scope.leftBarTabs.menuItems).isDisabled = false;//enabled click on general tab (DE246274)
412                 this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
413                 let modalInstance:ng.ui.bootstrap.IModalServiceInstance;
414                 modalInstance && modalInstance.close();  // Close the modal in case it is opened.
415                 this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);// for fix DE246217
416
417                 this.$scope.setValidState(true);  // Set the form valid (if sent form is valid, the error from server).
418             };
419
420             let onSuccessCreate = (component:Component) => {
421
422                 this.$scope.stopProgress();
423                 this.showSuccessNotificationMessage();
424
425                 // Update the components list for breadcrumbs
426                 this.components.unshift(component);
427
428                 this.$state.go(States.WORKSPACE_GENERAL, {
429                     id: component.uniqueId,
430                     type: component.componentType.toLowerCase(),
431                     components: this.components
432                 }, {inherit: false});
433             };
434
435             this.ComponentFactory.createComponentOnServer(this.$scope.component).then(onSuccessCreate, onFailed);
436
437
438         };
439
440         this.$scope.save = ():Promise<void> => {
441
442             this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_CLICK);
443
444             this.$scope.startProgress("Updating Asset...");
445             this.$scope.disableMenuItems();
446
447             return new Promise<void>((resolve, reject) => {
448                 let stopProgressAndEnableUI = () => {
449                     this.$scope.disabledButtons = false;
450                     this.$scope.isLoading = false;
451                     this.$scope.enableMenuItems();
452                     this.$scope.stopProgress();
453                 }
454
455                 let onFailed = () => {
456                     stopProgressAndEnableUI();
457                     this.$scope.updateUnsavedFileFlag(true);
458                     this.EventListenerService.notifyObservers(EVENTS.ON_WORKSPACE_SAVE_BUTTON_ERROR);
459
460                     reject();
461                 };
462
463                 let onSuccessUpdate = (component:Component) => {
464                     stopProgressAndEnableUI();
465                     this.showSuccessNotificationMessage();
466
467                     component.tags = _.reject(component.tags, (item)=> {
468                         return item === component.name
469                     });
470
471                     this.$scope.updateBreadcrumbs(component);
472
473                     //update the component
474                     this.$scope.setComponent(component);
475                     this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component);
476
477                     if (this.cacheService.contains(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
478                         this.cacheService.remove(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
479                     }
480                     if (this.cacheService.contains(PREVIOUS_CSAR_COMPONENT)) {
481                         this.cacheService.remove(PREVIOUS_CSAR_COMPONENT);
482                     }
483
484                     //clear edit flags
485                     this.$state.current.data.unsavedChanges = false;
486                     this.$scope.unsavedFile = false;
487                     this.$scope.reload(component);
488                     resolve();
489                 };
490
491                 this.$scope.component.updateComponent().then(onSuccessUpdate, onFailed);
492             });
493
494         };
495
496         this.$scope.changeLifecycleState = (state:string):void => {
497             if (this.$scope.isGeneralView() && state !== 'deleteVersion') {
498                 this.EventListenerService.notifyObservers(EVENTS.ON_LIFECYCLE_CHANGE_WITH_SAVE, state);
499             } else {
500                 this.$scope.handleChangeLifecycleState(state);
501             }
502         };
503
504         let defaultActionAfterChangeLifecycleState = ():void => {
505             if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
506                 this.$state.current.data.unsavedChanges = false;
507             }
508             this.$state.go('dashboard');
509         };
510
511         this.$scope.handleChangeLifecycleState = (state:string, newCsarVersion?:string, onError?: Function) => {
512             if ('monitor' === state) {
513                 this.$state.go('workspace.distribution');
514                 return;
515             }
516
517             let data = this.$scope.changeLifecycleStateButtons[state];
518             if (!data && this.$stateParams.componentCsar && !this.$scope.isCreateMode()) {
519                 data = {text: 'Check Out', url: 'lifecycleState/CHECKOUT'};
520             }
521             const onSuccess = (component, url:string):void => {
522                 // Updating the component from server response
523  
524                 // Creating the data object to notify the plugins with
525                 const eventData: any = {
526                     uuid: this.$scope.component.uuid,
527                     version: this.$scope.component.version
528                 };
529
530                 // the server returns only metaData (small component) except checkout (Full component)  ,so we update only the statuses of distribution & lifecycle
531                 this.$scope.component.lifecycleState = component.lifecycleState;
532                 this.$scope.component.distributionStatus = component.distributionStatus;
533
534                 switch (url) {
535                     case 'lifecycleState/CHECKOUT':
536                         this.workspaceNg1BridgeService.updateIsViewOnly(false);
537                         this.eventBusService.notify("CHECK_OUT", eventData, false).subscribe(() => {
538                             // only checkOut get the full component from server
539                             //   this.$scope.component = component;
540                             // Work around to change the csar version
541                             if(newCsarVersion) {
542                                 this.cacheService.set(CHANGE_COMPONENT_CSAR_VERSION_FLAG, newCsarVersion);
543                                 (this.$scope.component as Resource).csarVersion = newCsarVersion;
544                             }
545
546                             //when checking out a minor version uuid remains
547                             const bcIdx = _.findIndex(this.components, (item) => {
548                                 return item.uuid === component.uuid;
549                             });
550                             if (bcIdx !== -1) {
551                                 this.components[bcIdx] = component;
552                             } else {
553                                 //when checking out a major(certified) version
554                                 this.components.unshift(component);
555                             }
556                             this.$scope.mode = this.initViewMode();
557                             this.initChangeLifecycleStateButtons();
558                             this.initVersionObject();
559                             this.$scope.isLoading = false;
560                             this.EventListenerService.notifyObservers(EVENTS.ON_CHECKOUT, component);
561                             this.workspaceService.setComponentMetadata(component);
562
563                             this.Notification.success({
564                                 message: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TEXT"),
565                                 title: this.$filter('translate')("CHECKOUT_SUCCESS_MESSAGE_TITLE")
566                             });
567
568                         });
569                         break;
570                     case 'lifecycleState/CHECKIN':
571                         this.workspaceNg1BridgeService.updateIsViewOnly(true);
572                         defaultActionAfterChangeLifecycleState();
573                         this.Notification.success({
574                             message: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TEXT"),
575                             title: this.$filter('translate')("CHECKIN_SUCCESS_MESSAGE_TITLE")
576                         });
577                         break;
578                     case 'lifecycleState/UNDOCHECKOUT':
579                         this.eventBusService.notify("UNDO_CHECK_OUT", eventData, false).subscribe(() => {
580                             defaultActionAfterChangeLifecycleState();
581                             this.Notification.success({
582                                 message: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TEXT"),
583                                 title: this.$filter('translate')("DELETE_SUCCESS_MESSAGE_TITLE")
584                             });
585                         });
586                         break;
587                     case 'lifecycleState/certify':
588                         this.$scope.handleCertification(component);
589                         this.verifyIfDependenciesExist();
590                         this.$scope.reload(component);
591                         break;
592                     case 'distribution/PROD/activate':
593                         this.Notification.success({
594                             message: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TEXT"),
595                             title: this.$filter('translate')("DISTRIBUTE_SUCCESS_MESSAGE_TITLE")
596                         });
597                         this.initChangeLifecycleStateButtons();
598                         break;
599                     default :
600                         defaultActionAfterChangeLifecycleState();
601                 }
602                 if (data.url !== 'lifecycleState/CHECKOUT') {
603                     this.$scope.isLoading = false;
604                 }
605             };
606             this.ChangeLifecycleStateHandler.changeLifecycleState(this.$scope.component, data, this.$scope, onSuccess);
607         };
608
609
610
611         this.$scope.isViewMode = ():boolean => {
612             return this.$scope.mode === WorkspaceMode.VIEW;
613         };
614
615         this.$scope.isDesigner = ():boolean => {
616             return this.role == Role.DESIGNER;
617         };
618
619         this.$scope.isDisableMode = ():boolean => {
620             return this.$scope.mode === WorkspaceMode.VIEW && this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKIN;
621         };
622
623         this.$scope.isGeneralView = ():boolean => {
624             //we show revert and save icons only in general view
625             return this.$state.current.name === States.WORKSPACE_GENERAL;
626         };
627
628         this.$scope.isCreateMode = ():boolean => {
629             return this.$scope.mode === WorkspaceMode.CREATE;
630         };
631
632         this.$scope.checkDisableButton = (button: any):boolean => {
633             // Logic moved from html to component
634             if (this.$scope.isCreateMode() || button.disabled || this.$scope.disabledButtons || !this.$scope.isValidForm || this.$scope.unsavedChanges || this.$scope.component.archived){
635                 return true;
636             }
637
638             // Specific verification for Checkout - enabled only in case the component is the latest version.
639             let result: boolean = false;
640
641             if (button.url === 'lifecycleState/CHECKOUT') {
642                 result = !this.$scope.component.isLatestVersion();
643             }
644             return result;
645         };
646
647         this.$scope.isEditMode = ():boolean => {
648             return this.$scope.mode === WorkspaceMode.EDIT;
649         };
650
651         this.$scope.goToBreadcrumbHome = ():void => {
652             let bcHome:MenuItemGroup = this.$scope.breadcrumbsModel[0];
653             this.$state.go(bcHome.menuItems[bcHome.selectedIndex].state);
654         };
655
656         this.$scope.showLifecycleIcon = ():boolean => {
657             return this.role == Role.DESIGNER;
658         };
659
660         this.$scope.getStatus = ():string => {
661             if (this.$scope.isCreateMode()) {
662                 return 'IN DESIGN';
663             }
664
665             return this.$scope.component.getStatus(this.sdcMenu);
666         };
667
668         this.initMenuItems();
669
670         this.$scope.showLatestVersion = (): boolean => {
671             let result: boolean = true;
672             if (!this.$scope.component.isLatestVersion()) {
673                 result = false;
674             }
675             if (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) {
676                 result = false;
677             }
678             return result;
679         };
680
681         this.$scope.updateSelectedMenuItem = (state:string):void => {
682             let stateArray:Array<string> = state.split('.', 2);
683             let stateWithoutInternalNavigate:string = stateArray[0] + '.' + stateArray[1];
684             let selectedItem:MenuItem = _.find(this.$scope.leftBarTabs.menuItems, (item:MenuItem) => {
685                 let itemStateArray:Array<string> = item.state.split('.', 2);
686                 let itemStateWithoutNavigation:string = itemStateArray[0] + '.' + itemStateArray[1];
687                 return (itemStateWithoutNavigation === stateWithoutInternalNavigate);
688             });
689
690             let selectedIndex = selectedItem ? this.$scope.leftBarTabs.menuItems.indexOf(selectedItem) : 0;
691
692             if (stateArray[1] === 'plugins') {
693                 _.forEach(PluginsConfiguration.plugins, (plugin) => {
694                     if (plugin.pluginStateUrl == this.$state.params.path) {
695                         return false;
696                     }
697                     else if (this.pluginsService.isPluginDisplayedInContext(plugin, this.role, this.$scope.component.getComponentSubType())) {
698                         selectedIndex++;
699                     }
700                 });
701             }
702
703             this.$scope.leftBarTabs.selectedIndex = selectedIndex;
704         };
705
706         this.$scope.isSelected = (menuItem: MenuItem): boolean => {
707             return this.$scope.leftBarTabs.selectedIndex === _.indexOf(this.$scope.leftBarTabs.menuItems, menuItem);
708         };
709
710         this.$scope.$watch('$state.current.name', (newVal: string): void => {
711             if (newVal) {
712                 this.$scope.isComposition = (newVal.indexOf(States.WORKSPACE_COMPOSITION) > -1);
713                 this.$scope.isDeployment = newVal == States.WORKSPACE_DEPLOYMENT;
714                 this.$scope.isPlugins = newVal == States.WORKSPACE_PLUGINS;
715             }
716         });
717
718         this.$scope.getTabTitle = (): string => {
719             return this.$scope.leftBarTabs.menuItems.find((menuItem: MenuItem) => {
720                 return menuItem.state == this.$scope.$state.current.name;
721             }).text;
722         };
723
724         this.$scope.reload = (component: Component): void => {
725             const isGeneralTab = this.$state.current.name === 'workspace.general';
726             // nullify the componentCsar in case we are in general tab so we know we didnt came from updateVsp Modal
727             if (isGeneralTab) {
728                 this.$state.go(this.$state.current.name, {id: component.uniqueId, componentCsar: null}, {reload: true});
729             } else {
730                 this.$state.go(this.$state.current.name, {id: component.uniqueId}, {reload: true});
731             }
732         };
733
734         this.$scope.$on('$destroy', () => {
735             this.EventListenerService.unRegisterObserver(EVENTS.ON_WORKSPACE_UNSAVED_CHANGES);
736         });
737
738         this.$scope.openAutomatedUpgradeModal = ():void => {
739             this.$scope.isLoading = true;
740             this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response:Array<IDependenciesServerResponse>)=> {
741                 this.$scope.isLoading = false;
742                 this.AutomatedUpgradeService.openAutomatedUpgradeModal(response, this.$scope.component, false);
743             });
744         }
745
746         this.$scope.handleCertification = (certifyComponent): void => {
747             if (this.$scope.component.getComponentSubType() === ResourceType.VF || this.$scope.component.isService()) {
748                 this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response:Array<IDependenciesServerResponse>) => {
749                     this.$scope.isLoading = false;
750
751                     const isUpgradeNeeded = _.filter(response, (componentToUpgrade:IDependenciesServerResponse) => {
752                         return componentToUpgrade.dependencies && componentToUpgrade.dependencies.length > 0;
753                     });
754                     if (isUpgradeNeeded.length === 0) {
755                         this.onSuccessWithoutUpgradeNeeded();
756                         return;
757                     }
758                     this.refreshDataAfterChangeLifecycleState(certifyComponent);
759                     this.AutomatedUpgradeService.openAutomatedUpgradeModal(response, this.$scope.component, true);
760                 });
761             } else {
762                 this.onSuccessWithoutUpgradeNeeded();
763             }
764         }
765
766         this.$scope.disableMenuItems = () => {
767             this.$scope.leftBarTabs.menuItems.forEach((item: MenuItem) => {
768                 item.isDisabled = (States.WORKSPACE_GENERAL !== item.state);
769             });
770         }
771
772         this.$scope.enableMenuItems = () => {
773             this.$scope.leftBarTabs.menuItems.forEach((item: MenuItem) => {
774                 item.isDisabled = false;
775             });
776         };
777
778
779         this.$scope.startProgress = (message: string): void => {
780             this.progressService.initCreateComponentProgress(this.$scope.component.uniqueId);
781             this.$scope.isCreateProgress = true;
782             this.$scope.progressMessage = message;
783         };
784
785         this.$scope.stopProgress = (): void => {
786             this.$scope.isCreateProgress = false;
787             this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
788         }
789
790         this.$scope.updateBreadcrumbs = (component: Component): void => {
791             // Update the components list for breadcrumbs
792             const bcIdx = this.MenuHandler.findBreadcrumbComponentIndex(this.components, component);
793             if (bcIdx !== -1) {
794                 this.components[bcIdx] = component;
795                 this.initBreadcrumbs();  // re-calculate breadcrumbs
796             }
797         };
798
799         this.$scope.updateUnsavedFileFlag = (isUnsaved:boolean) => {
800             this.$scope.unsavedFile = isUnsaved;
801         };
802
803     }
804
805     private onSuccessWithoutUpgradeNeeded = (): void => {
806         this.$scope.isLoading = false;
807         this.Notification.success({
808             message: this.$filter('translate')('SERVICE_CERTIFICATION_STATUS_TEXT'),
809             title: this.$filter('translate')('SERVICE_CERTIFICATION_STATUS_TITLE')
810         });
811         this.initVersionObject();
812         this.initChangeLifecycleStateButtons();
813     }
814
815     private refreshDataAfterChangeLifecycleState = (component:Component):void => {
816         this.$scope.isLoading = false;
817         this.$scope.mode = this.initViewMode();
818         this.initChangeLifecycleStateButtons();
819         this.initVersionObject();
820         this.EventListenerService.notifyObservers(EVENTS.ON_LIFECYCLE_CHANGE, component);
821     }
822
823     private initAfterScope = (): void => {
824         // In case user select csar from the onboarding modal, need to disable checkout and submit for testing.
825         if (this.$state.params['disableButtons'] === true) {
826             this.$scope.uploadFileChangedInGeneralTab();
827         }
828     };
829
830     private initVersionObject = (): void => {
831         this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse();
832         this.$scope.changeVersion = {
833             selectedVersion: _.find(this.$scope.versionsList, (versionObj) => {
834                 return versionObj.versionId === this.$scope.component.uniqueId;
835             })
836         };
837     }
838
839     private getNewComponentBreadcrumbItem = (): MenuItem => {
840         let text = '';
841         if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
842             text = this.$scope.component.getComponentSubType() + ': ' + this.$scope.component.name;
843         } else {
844             text = 'Create new ' + this.$state.params['type'];
845         }
846         return new MenuItem(text, null, States.WORKSPACE_GENERAL, 'goToState', [this.$state.params]);
847     }
848
849     private updateMenuItemByRole = (menuItems: any[], role: string) => {
850         const tempMenuItems: any[] = new Array<any>();
851         menuItems.forEach((item: any) => {
852             //remove item if role is disabled
853             if (!(item.disabledRoles && item.disabledRoles.indexOf(role) > -1)) {
854                 tempMenuItems.push(item);
855             }
856         });
857         return tempMenuItems;
858     }
859
860         private updateMenuItemByCategory = (menuItems:Array<any>, category:string) => {
861         let tempMenuItems:Array<any> = new Array<any>();
862         menuItems.forEach((item:any) => {
863             //update flag disabledCategory to true if category is disabled
864             item.disabledCategory = false;
865             if ((item.disabledCategories && item.disabledCategories.indexOf(category) > -1))
866             {
867                 item.disabledCategory = true;
868             }
869             tempMenuItems.push(item);
870         });
871         return tempMenuItems;
872     };
873
874
875     private deleteArchiveCache = () => {
876         this.cacheService.remove('archiveComponents'); // delete the cache to ensure the archive is reloaded from server
877     }
878
879     private initBreadcrumbs = () => {
880         this.components = this.cacheService.get('breadcrumbsComponents');
881         const breadcrumbsComponentsLvl = this.MenuHandler.generateBreadcrumbsModelFromComponents(this.components, this.$scope.component);
882
883         if (this.$scope.isCreateMode()) {
884             const createItem = this.getNewComponentBreadcrumbItem();
885             if (!breadcrumbsComponentsLvl.menuItems) {
886                 breadcrumbsComponentsLvl.menuItems = [];
887             }
888             breadcrumbsComponentsLvl.menuItems.unshift(createItem);
889             breadcrumbsComponentsLvl.selectedIndex = 0;
890         }
891
892         this.$scope.breadcrumbsModel = [breadcrumbsComponentsLvl, this.$scope.leftBarTabs];
893     }
894
895     private initMenuItems() {
896
897         const inCreateMode = this.$scope.isCreateMode();
898         this.$scope.leftBarTabs = new MenuItemGroup();
899         let menuItemsObjects: any[] = this.updateMenuItemByRole(this.sdcMenu.component_workspace_menu_option[this.$scope.component.getComponentSubType()], this.role);
900         if (this.$scope.component.getComponentSubType() === 'SERVICE') {
901             const menuItemsObjectsCategory: any[] = this.updateMenuItemByCategory(menuItemsObjects, this.category);
902             menuItemsObjects = menuItemsObjectsCategory;
903         }
904
905         // Only adding plugins to the workspace if they can be displayed for the current user role
906         _.each(PluginsConfiguration.plugins, (plugin: Plugin) => {
907             if (this.pluginsService.isPluginDisplayedInContext(plugin, this.role, this.$scope.component.getComponentSubType())) {
908                 menuItemsObjects.push({
909                     text: plugin.pluginDisplayOptions['context'].displayName,
910                     action: 'onMenuItemPressed',
911                     state: 'workspace.plugins',
912                     params: {path: plugin.pluginStateUrl}
913                 });
914             }
915         });
916
917         this.$scope.leftBarTabs.menuItems = menuItemsObjects.map((item: MenuItem) => {
918             const menuItem = new MenuItem(item.text, item.callback, item.state, item.action, item.params, item.blockedForTypes, item.disabledCategory);
919             if (menuItem.params) {
920                 menuItem.params.state = menuItem.state;
921             }
922             else {
923                 menuItem.params = {state: menuItem.state};
924             }
925             menuItem.callback = () => this.$scope[menuItem.action](menuItem.state, menuItem.params);
926             menuItem.isDisabled = (inCreateMode && States.WORKSPACE_GENERAL !== menuItem.state) ||
927                 (States.WORKSPACE_DEPLOYMENT === menuItem.state && this.$scope.component.modules
928                 && this.$scope.component.modules.length === 0 && this.$scope.component.isResource()) ||
929                 (menuItem.disabledCategory === true);
930             return menuItem;
931         });
932
933         if (this.cacheService.get('breadcrumbsComponents')) {
934             this.initBreadcrumbs();
935         }
936         else {
937             this.initBreadcrumbsComponents();
938         }
939     }
940
941     private showSuccessNotificationMessage = ():void => {
942         this.Notification.success({
943             message: this.$filter('translate')('IMPORT_VF_MESSAGE_CREATE_FINISHED_DESCRIPTION'),
944             title: this.$filter('translate')('IMPORT_VF_MESSAGE_CREATE_FINISHED_TITLE')
945         });
946     }
947
948     private setWorkspaceButtonState = (newState: boolean, callback?: Function) => {
949         this.$scope.unsavedChanges = newState;
950         this.$scope.unsavedChangesCallback = callback;
951     }
952
953     private initBreadcrumbsComponents = (): void => {
954         let breadcrumbsComponentsObservable;
955         if (this.$stateParams.previousState === 'dashboard') {
956             breadcrumbsComponentsObservable = this.homeService.getAllComponents(true);
957         } else if (this.$stateParams.previousState === 'catalog') {
958             breadcrumbsComponentsObservable = this.catalogService.getCatalog();
959         } else {
960             this.cacheService.remove('breadcrumbsComponentsState');
961             this.cacheService.remove('breadcrumbsComponents');
962             return;
963         }
964         breadcrumbsComponentsObservable.subscribe((components) => {
965             this.cacheService.set('breadcrumbsComponentsState', this.$stateParams.previousState);
966             this.cacheService.set('breadcrumbsComponents', components);
967             this.initBreadcrumbs();
968         });
969
970     }
971
972     private verifyIfDependenciesExist(): void {
973         let containsDependencies = [];
974         if (this.$scope.component.componentType && this.$scope.component.uniqueId &&
975             this.$scope.component.lifecycleState === 'CERTIFIED' && (this.$scope.component.isService() || this.$scope.component.getComponentSubType() === 'VF')) {
976             this.ComponentServiceNg2.getDependencies(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response: IDependenciesServerResponse[]) => {
977                 containsDependencies = response.filter((version) => version.dependencies);
978                 if (containsDependencies.length > 0) {
979                     this.$scope.hasNoDependencies = false;
980                 } else {
981                     this.$scope.hasNoDependencies = true;
982                 }
983             });
984         }
985     }
986 }