Dynamic columns in GAB table
[sdc.git] / catalog-ui / src / app / view-models / workspace / tabs / deployment-artifacts / deployment-artifacts-view-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 //@require "./*.html"
23 'use strict';
24 import * as _ from "lodash";
25 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
26 import {ArtifactModel, ArtifactGroupModel, Resource} from "app/models";
27 import {ArtifactsUtils, ModalsHandler, ValidationUtils} from "app/utils";
28 import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
29 import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
30 import {GenericArtifactBrowserComponent} from "../../../../ng2/components/logic/generic-artifact-browser/generic-artifact-browser.component";
31 import {PathsAndNamesDefinition} from "../../../../models/paths-and-names";
32 import {ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service";
33 import {IModalConfig} from "sdc-ui/lib/angular/modals/models/modal-config";
34 import {CacheService} from "../../../../services/cache-service";
35 import {GabConfig} from "../../../../models/gab-config";
36
37 interface IDeploymentArtifactsViewModelScope extends IWorkspaceViewModelScope {
38     tableHeadersList:Array<any>;
39     reverse:boolean;
40     sortBy:string;
41     artifacts:Array<ArtifactModel>;
42     editForm:ng.IFormController;
43     isLoading:boolean;
44     artifactDescriptions:any;
45     selectedArtifactId:string;
46     popoverTemplate:string;
47
48     addOrUpdate(artifact:ArtifactModel):void;
49     updateSelectedArtifact():void;
50     delete(artifact:ArtifactModel):void;
51     sort(sortBy:string):void;
52     noArtifactsToShow():boolean;
53     getValidationPattern(validationType:string, parameterType?:string):RegExp;
54     validateJson(json:string):boolean;
55     resetValue(parameter:any):void;
56     viewModeOrCsarComponent():boolean;
57     isLicenseArtifact(artifact:ArtifactModel):void;
58     getEnvArtifact(heatArtifact:ArtifactModel):ArtifactModel;
59     getEnvArtifactName(artifact:ArtifactModel):string;
60     openEditEnvParametersModal(artifact:ArtifactModel):void;
61     openDescriptionPopover(artifactId:string):void;
62     closeDescriptionPopover():void;
63 }
64
65 export class DeploymentArtifactsViewModel {
66
67     static '$inject' = [
68         '$scope',
69         '$templateCache',
70         '$filter',
71         'Sdc.Services.CacheService',
72         'ValidationUtils',
73         'ArtifactsUtils',
74         'ModalsHandler',
75         'ComponentServiceNg2',
76         'ModalServiceSdcUI'
77     ];
78
79     constructor(private $scope:IDeploymentArtifactsViewModelScope,
80                 private $templateCache:ng.ITemplateCacheService,
81                 private $filter:ng.IFilterService,
82                 private cacheService:CacheService,
83                 private validationUtils:ValidationUtils,
84                 private artifactsUtils:ArtifactsUtils,
85                 private ModalsHandler:ModalsHandler,
86                 private ComponentServiceNg2: ComponentServiceNg2,
87                 private ModalServiceSdcUI: ModalServiceSdcUI) {
88         this.initScope();
89     }
90
91     private initDescriptions = ():void => {
92         this.$scope.artifactDescriptions = {};
93         _.forEach(this.$scope.component.deploymentArtifacts, (artifact:ArtifactModel):void => {
94             this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description;
95         });
96     };
97
98     private setArtifact = (artifact:ArtifactModel):void => {
99         if (!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)) {
100             artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel];
101         }
102     };
103
104     private initScopeArtifacts = ()=> {
105         this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
106         _.forEach(this.$scope.artifacts, (artifact:ArtifactModel):void => {
107             artifact.envArtifact = this.getEnvArtifact(artifact);
108         });
109     };
110
111     private initArtifacts = (loadFromServer:boolean):void => {
112         if (loadFromServer) {
113             this.$scope.isLoading = true;
114             this.ComponentServiceNg2.getComponentDeploymentArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
115                 this.$scope.component.deploymentArtifacts = response.deploymentArtifacts;
116                 this.initScopeArtifacts();
117                 this.$scope.isLoading = false;
118             });
119         } else {
120             this.initScopeArtifacts();
121         }
122
123     };
124
125     private getEnvArtifact = (heatArtifact:ArtifactModel):ArtifactModel=> {
126         return _.find(this.$scope.artifacts, (item:ArtifactModel)=> {
127             return item.generatedFromId === heatArtifact.uniqueId;
128         });
129     };
130
131     private getCurrentArtifact = ():ArtifactModel => {
132         if (!this.$scope.selectedArtifactId) {
133             return null;
134         }
135         let artifact:ArtifactModel = this.$scope.artifacts.filter((art) => {
136             return art.uniqueId == this.$scope.selectedArtifactId;
137         })[0];
138         return artifact;
139     }
140
141     private initScope = ():void => {
142         let self = this;
143         this.$scope.isLoading = false;
144         this.$scope.selectedArtifactId = null;
145         this.initDescriptions();
146         if(this.$scope.component.deploymentArtifacts) {
147             this.initArtifacts(false);
148         } else {
149             this.initArtifacts(true);
150         }
151         this.$scope.setValidState(true);
152
153         this.$scope.tableHeadersList = [
154             {title: 'Name', property: 'artifactDisplayName'},
155             {title: 'Type', property: 'artifactType'},
156             {title: 'Deployment timeout', property: 'timeout'},
157             {title: 'Version', property: 'artifactVersion'},
158             {title: 'UUID', property: 'artifactUUID'}
159         ];
160
161         this.$templateCache.put("deployment-artifacts-description-popover.html", require('app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html'));
162         this.$scope.popoverTemplate = "deployment-artifacts-description-popover.html";
163
164         this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => {
165             let isLicense:boolean = false;
166             if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
167
168                 isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
169             }
170
171             return isLicense;
172         };
173
174         this.$scope.sort = (sortBy:string):void => {
175             this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
176             this.$scope.sortBy = sortBy;
177         };
178
179         this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
180             return this.validationUtils.getValidationPattern(validationType, parameterType);
181         };
182
183         this.$scope.validateJson = (json:string):boolean => {
184             if (!json) {
185                 return true;
186             }
187             return this.validationUtils.validateJson(json);
188         };
189
190         this.$scope.viewModeOrCsarComponent = ():boolean => {
191             return this.$scope.isViewMode() || (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent());
192         };
193
194         this.$scope.addOrUpdate = (artifact:ArtifactModel):void => {
195             artifact.artifactGroupType = 'DEPLOYMENT';
196             let artifactCopy = new ArtifactModel(artifact);
197
198             let success = (response:any):void => {
199                 this.$scope.artifactDescriptions[artifactCopy.artifactLabel] = artifactCopy.description;
200                 this.initArtifacts(true);
201                 //  this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
202             };
203
204             let error = (err:any):void => {
205                 console.log(err);
206                 this.initArtifacts(true);
207                 //  self.$scope.artifacts = _.values(self.$scope.component.deploymentArtifacts);
208             };
209
210             this.ModalsHandler.openArtifactModal(artifactCopy, this.$scope.component).then(success, error);
211         };
212
213         this.$scope.noArtifactsToShow = ():boolean => {
214             return !_.some(this.$scope.artifacts, 'esId');
215         };
216
217         this.$scope.resetValue = (parameter:any):void => {
218             if (!parameter.currentValue && parameter.defaultValue) {
219                 parameter.currentValue = parameter.defaultValue;
220             }
221             else if ('boolean' == parameter.type) {
222                 parameter.currentValue = parameter.currentValue.toUpperCase();
223             }
224         };
225
226         this.$scope.$watch('editForm.$valid', ():void => {
227             if (this.$scope.editForm) {
228                 //    this.$scope.setValidState(this.$scope.editForm.$valid);
229             }
230         });
231
232         this.$scope.updateSelectedArtifact = ():void => {
233             if (!this.$scope.isViewMode() && !this.$scope.isLoading) {
234                 let artifact:ArtifactModel = this.getCurrentArtifact();
235                 this.setArtifact(artifact); //resets artifact description to original value if invalid.
236                 if (artifact && artifact.originalDescription != artifact.description) {
237                     this.$scope.isLoading = true;
238                     let onSuccess = (responseArtifact:ArtifactModel):void => {
239                         this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description;
240                         // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
241                         this.initArtifacts(true);
242                         this.$scope.isLoading = false;
243                     };
244
245                     let onFailed = (error:any):void => {
246                         console.log('Delete artifact returned error:', error);
247                         this.$scope.isLoading = false;
248                     };
249
250                     this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed);
251                 }
252             }
253         };
254
255         this.$scope.delete = (artifact:ArtifactModel):void => {
256             let onOk = ():void => {
257                 this.$scope.isLoading = true;
258                 let onSuccess = ():void => {
259                     this.$scope.isLoading = false;
260                     this.initArtifacts(true);
261                     //this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
262                 };
263
264                 let onFailed = (error:any):void => {
265                     this.$scope.isLoading = false;
266                     console.log('Delete artifact returned error:', error);
267                 };
268
269                 this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
270             };
271
272             let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
273             let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
274             this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
275         };
276
277         this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => {
278             let envArtifact = this.$scope.getEnvArtifact(artifact);
279             if (envArtifact) {
280                 return envArtifact.artifactDisplayName;
281             }
282         };
283
284         this.$scope.openGenericArtifactBrowserModal = (artifact:ArtifactModel):void => {
285             let self = this;
286             const title = 'Generic Artifact Browser';
287             let modalConfig: IModalConfig = {
288                 size: 'xl',
289                 title: title,
290                 type: 'custom',
291                 buttons: [{
292                         id: 'closeGABButton',
293                         text: 'Close',
294                         size: "'x-small'",
295                         closeModal: true
296                     }]
297             };
298
299             const uiConfiguration: any = this.cacheService.get('UIConfiguration');
300             let noConfig: boolean = false;
301             let pathsandnames: PathsAndNamesDefinition[] = [];
302
303             if(typeof uiConfiguration.gab === 'undefined') {
304                 noConfig = true
305             } else {
306                 const gabConfig: GabConfig = uiConfiguration.gab
307                     .find(config => config.artifactType === artifact.artifactType);
308                 if(typeof gabConfig === 'undefined') {
309                     noConfig = true;
310                 } else {
311                     pathsandnames = gabConfig.pathsAndNamesDefinitions;
312                 }
313             }
314
315             if(noConfig) {
316                 const msg = self.$filter('translate')("DEPLOYMENT_ARTIFACT_GAB_NO_CONFIG");
317                 this.ModalServiceSdcUI.openAlertModal(title, msg);
318             }
319
320             const modalInputs = {
321                 pathsandnames: pathsandnames,
322                 artifactid: artifact.esId,
323                 resourceid: this.$scope.component.uniqueId
324             };
325
326             this.ModalServiceSdcUI.openCustomModal(modalConfig, GenericArtifactBrowserComponent, modalInputs);
327         };
328
329         this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => {
330             this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.component).then(()=> {
331                 this.initArtifacts(true);
332             }, ()=> {
333                 this.initArtifacts(true);
334             });
335         };
336
337         this.$scope.openDescriptionPopover = (artifactId:string):void => {
338             if (this.$scope.selectedArtifactId && this.$scope.selectedArtifactId != artifactId) {
339                 this.$scope.updateSelectedArtifact();
340             }
341             this.$scope.selectedArtifactId = artifactId;
342
343         };
344
345         this.$scope.closeDescriptionPopover = ():void => {
346             if (this.$scope.selectedArtifactId) {
347                 this.$scope.updateSelectedArtifact();
348                 this.$scope.selectedArtifactId = null;
349             }
350         };
351     };
352 }