CSIT Fix for SDC-2585
[sdc.git] / catalog-ui / src / app / view-models / modals / onboarding-modal / onboarding-modal-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 'use strict';
22 import {ComponentType, SEVERITY, FileUtils, ModalsHandler, ComponentFactory} from "app/utils";
23 import {OnboardingService, CacheService} from "app/services";
24 import {Component, IComponent, IUser, IAppConfigurtaion, Resource} from "app/models";
25 import {IServerMessageModalModel} from "../message-modal/message-server-modal/server-message-modal-view-model";
26 import {Dictionary} from "app/utils";
27 import * as _ from 'underscore';
28
29 interface IOnboardingModalViewModelScope {
30     modalOnboarding:ng.ui.bootstrap.IModalServiceInstance;
31     componentsList:Array<IComponent>;
32     tableHeadersList:Array<any>;
33     selectedComponent:Component;
34     componentFromServer:Component;
35     reverse:boolean;
36     sortBy:string;
37     searchBind:string;
38     okButtonText:string;
39     isCsarComponentExists:boolean;
40     user:IUser;
41     isLoading:boolean;
42
43     //this is for UI paging
44     numberOfItemsToDisplay:number;
45     allItemsDisplayed:boolean;
46
47     doSelectComponent(component:Component):void;
48     doUpdateCsar():void;
49     doImportCsar():void;
50     sort(sortBy:string):void;
51     downloadCsar(packageId:string):void;
52     increaseNumItemsToDisplay():void;
53 }
54
55 export class OnboardingModalViewModel {
56
57     static '$inject' = [
58         '$scope',
59         '$filter',
60         '$state',
61         'sdcConfig',
62         '$uibModalInstance',
63         'Sdc.Services.OnboardingService',
64         'okButtonText',
65         'currentCsarUUID',
66         'currentCsarVersion',
67         'Sdc.Services.CacheService',
68         'FileUtils',
69         'ComponentFactory',
70         'ModalsHandler'
71     ];
72
73     constructor(private $scope:IOnboardingModalViewModelScope,
74                 private $filter:ng.IFilterService,
75                 private $state:any,
76                 private sdcConfig:IAppConfigurtaion,
77                 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
78                 private onBoardingService:OnboardingService,
79                 private okButtonText:string,
80                 private currentCsarUUID:string,
81                 private currentCsarVersion:string,
82                 private cacheService:CacheService,
83                 private fileUtils:FileUtils,
84                 private componentFactory:ComponentFactory,
85                 private modalsHandler:ModalsHandler) {
86
87         this.init();
88     }
89
90     /**
91      * Called from controller constructor, this will call onboarding service to get list
92      * of "mini" components (empty components created from CSAR).
93      * The list is inserted to componentsList on $scope.
94      * And then call initScope method.
95      */
96     private init = ():void => {
97         this.initOnboardingComponentsList();
98     };
99
100     private initScope = ():void => {
101
102         this.initSortedTableScope();
103         this.initModalScope();
104         this.$scope.sortBy = "name"; // Default sort by
105         this.$scope.user = this.cacheService.get('user');
106         this.$scope.okButtonText = this.okButtonText;
107         this.$scope.numberOfItemsToDisplay = 0;
108         this.$scope.allItemsDisplayed = false;
109
110         // Dismiss the modal and pass the "mini" component to workspace general page
111         this.$scope.doImportCsar = ():void => {
112
113             this.$uibModalInstance.close({
114                 componentCsar: this.$scope.selectedComponent,
115                 type: ComponentType.RESOURCE.toLowerCase()
116             });
117         };
118
119         this.$scope.doUpdateCsar = ():void => {
120             
121             // Change the component version to the CSAR version we want to update.
122             if(!this.currentCsarVersion || this.currentCsarVersion != (<Resource>this.$scope.selectedComponent).csarVersion) {
123                 this.$uibModalInstance.close({
124                     componentCsar: this.$scope.selectedComponent,
125                     previousComponent: this.$scope.componentFromServer,
126                     type: this.$scope.componentFromServer.componentType.toLowerCase()
127                     
128                 });
129
130             } else {
131                 this.$uibModalInstance.close();
132             }
133         };
134
135         this.$scope.downloadCsar = (packageId:string):void => {
136             this.$scope.isLoading = true;
137             this.onBoardingService.downloadOnboardingCsar(packageId).then(
138                 (file:any):void => {
139                     this.$scope.isLoading = false;
140                     if (file) {
141                         this.fileUtils.downloadFile(file, packageId + '.csar');
142                     }
143                 }, ():void => {
144                     this.$scope.isLoading = false;
145                     var data:IServerMessageModalModel = {
146                         title: 'Download error',
147                         message: "Error downloading file",
148                         severity: SEVERITY.ERROR,
149                         messageId: "",
150                         status: ""
151                     };
152                     this.modalsHandler.openServerMessageModal(data);
153                 }
154             );
155         };
156
157         this.$scope.increaseNumItemsToDisplay = ():void => {
158             this.$scope.numberOfItemsToDisplay = this.$scope.numberOfItemsToDisplay + 40;
159             if (this.$scope.componentsList) {
160                 this.$scope.allItemsDisplayed = this.$scope.numberOfItemsToDisplay >= this.$scope.componentsList.length;
161             }
162         };
163
164         // When the user select a row, set the component as selectedComponent
165         this.$scope.doSelectComponent = (component:Component):void => {
166
167             if (this.$scope.selectedComponent === component) {
168                 // Collapse the item
169                 this.$scope.selectedComponent = undefined;
170                 return;
171             }
172
173             this.$scope.isLoading = true;
174             this.$scope.componentFromServer = undefined;
175             this.$scope.selectedComponent = component;
176
177             let onSuccess = (componentFromServer:Component):void => {
178                 this.$scope.isLoading = false;
179                 if (componentFromServer) {
180                     this.$scope.componentFromServer = componentFromServer;
181                     this.$scope.isCsarComponentExists = true;
182                 } else {
183                     this.$scope.componentFromServer = component;
184                     this.$scope.isCsarComponentExists = false;
185                 }
186             };
187
188             let onError = ():void => {
189                 this.$scope.isLoading = false;
190                 this.$scope.componentFromServer = component;
191                 this.$scope.isCsarComponentExists = false;
192             };
193
194             this.onBoardingService.getComponentFromCsarUuid((<Resource>component).csarUUID).then(onSuccess, onError);
195         };
196
197     };
198
199     private initSortedTableScope = ():void => {
200         this.$scope.tableHeadersList = [
201             {title: 'Name', property: 'name'},
202             {title: 'Vendor', property: 'vendorName'},
203             {title: 'Category', property: 'categories'},
204             {title: 'Version', property: 'csarVersion'},
205             {title: 'Type', property: 'resourceType'},
206             {title: '#', property: 'importAndUpdate'}
207             //{title: 'Date', property: 'componentDate'}
208         ];
209
210         this.$scope.sort = (sortBy:string):void => {
211             this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
212             this.$scope.sortBy = sortBy;
213         };
214     };
215
216     private initModalScope = ():void => {
217         // Enable the modal directive to close
218         this.$scope.modalOnboarding = this.$uibModalInstance;
219     };
220
221     private initOnboardingComponentsList = ():void => {
222         let onSuccess = (onboardingResponse:Array<IComponent>):void => {
223             initMaxVersionOfItemsInList(onboardingResponse);
224
225             if (this.currentCsarUUID) {
226                 //this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList, {csarUUID: this.currentCsarUUID});
227                 this.$scope.componentsList = this.$filter('filter')(this.$scope.componentsList,
228                     (input):boolean => {
229                         return input.csarUUID === this.currentCsarUUID;
230                     }
231                 );
232             }
233             this.initScope();
234         };
235
236         let onError = ():void => {
237             console.log("Error getting onboarding list");
238             this.initScope();
239         };
240
241         let initMaxVersionOfItemsInList = (onboardingResponse:Array<IComponent>):void => {
242             // Get only the latest version of each item
243             this.$scope.componentsList = [];
244
245             // Get all unique items from the list
246             let uniqueItems:Array<any> = _.uniq(onboardingResponse, false, (item:any):void=>{
247                 return item.packageId;
248             });
249             
250             // Loop on all the items with unique packageId
251             _.each(uniqueItems, (item:any):void=> {
252                 // Find all the items that has same packageId
253                 let ItemsFound:Array<IComponent> = _.filter(onboardingResponse, (inListItem:any):any => {
254                     return inListItem.packageId === item.packageId;
255                 });
256
257                 // Loop on all the items with same packageId and find the max version.
258                 let maxItem:any;
259                 _.each(ItemsFound, (ItemFound:any):void=> {
260                     if (!maxItem) {
261                         maxItem = ItemFound;
262                     } else if (maxItem && parseInt(maxItem.csarVersion) < parseInt(ItemFound.csarVersion)) {
263                         maxItem = ItemFound;
264                     }
265                 });
266                 this.$scope.componentsList.push(maxItem);
267             });
268         };
269
270         this.onBoardingService.getOnboardingComponents().then(onSuccess, onError);
271     };
272 }