Sync Integ to Master
[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  * ================================================================================
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 //@require "./*.html"
22 'use strict';
23 import * as _ from "lodash";
24 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
25 import {ArtifactModel, ArtifactGroupModel, Resource} from "app/models";
26 import {ArtifactsUtils, ModalsHandler, ValidationUtils} from "app/utils";
27 import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
28 import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
29
30 interface IDeploymentArtifactsViewModelScope extends IWorkspaceViewModelScope {
31     tableHeadersList:Array<any>;
32     reverse:boolean;
33     sortBy:string;
34     artifacts:Array<ArtifactModel>;
35     editForm:ng.IFormController;
36     isLoading:boolean;
37     artifactDescriptions:any;
38     selectedArtifactId:string;
39     popoverTemplate:string;
40
41     addOrUpdate(artifact:ArtifactModel):void;
42     updateSelectedArtifact():void;
43     delete(artifact:ArtifactModel):void;
44     sort(sortBy:string):void;
45     noArtifactsToShow():boolean;
46     getValidationPattern(validationType:string, parameterType?:string):RegExp;
47     validateJson(json:string):boolean;
48     resetValue(parameter:any):void;
49     viewModeOrCsarComponent():boolean;
50     isLicenseArtifact(artifact:ArtifactModel):void;
51     getEnvArtifact(heatArtifact:ArtifactModel):ArtifactModel;
52     getEnvArtifactName(artifact:ArtifactModel):string;
53     openEditEnvParametersModal(artifact:ArtifactModel):void;
54     openDescriptionPopover(artifactId:string):void;
55     closeDescriptionPopover():void;
56 }
57
58 export class DeploymentArtifactsViewModel {
59
60     static '$inject' = [
61         '$scope',
62         '$templateCache',
63         '$filter',
64         'ValidationUtils',
65         'ArtifactsUtils',
66         'ModalsHandler',
67         'ComponentServiceNg2'
68     ];
69
70     constructor(private $scope:IDeploymentArtifactsViewModelScope,
71                 private $templateCache:ng.ITemplateCacheService,
72                 private $filter:ng.IFilterService,
73                 private validationUtils:ValidationUtils,
74                 private artifactsUtils:ArtifactsUtils,
75                 private ModalsHandler:ModalsHandler,
76                 private ComponentServiceNg2: ComponentServiceNg2) {
77         this.initScope();
78     }
79
80     private initDescriptions = ():void => {
81         this.$scope.artifactDescriptions = {};
82         _.forEach(this.$scope.component.deploymentArtifacts, (artifact:ArtifactModel):void => {
83             this.$scope.artifactDescriptions[artifact.artifactLabel] = artifact.description;
84         });
85     };
86
87     private setArtifact = (artifact:ArtifactModel):void => {
88         if (!artifact.description || !this.$scope.getValidationPattern('string').test(artifact.description)) {
89             artifact.description = this.$scope.artifactDescriptions[artifact.artifactLabel];
90         }
91     };
92
93     private initScopeArtifacts = ()=> {
94         this.$scope.artifacts = <ArtifactModel[]>_.values(this.$scope.component.deploymentArtifacts);
95         _.forEach(this.$scope.artifacts, (artifact:ArtifactModel):void => {
96             artifact.envArtifact = this.getEnvArtifact(artifact);
97         });
98     };
99
100     private initArtifacts = (loadFromServer:boolean):void => {
101         if (loadFromServer) {
102             this.$scope.isLoading = true;
103             this.ComponentServiceNg2.getComponentDeploymentArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
104                 this.$scope.component.deploymentArtifacts = response.deploymentArtifacts;
105                 this.initScopeArtifacts();
106                 this.$scope.isLoading = false;
107             });
108         } else {
109             this.initScopeArtifacts();
110         }
111
112     };
113
114     private getEnvArtifact = (heatArtifact:ArtifactModel):ArtifactModel=> {
115         return _.find(this.$scope.artifacts, (item:ArtifactModel)=> {
116             return item.generatedFromId === heatArtifact.uniqueId;
117         });
118     };
119
120     private getCurrentArtifact = ():ArtifactModel => {
121         if (!this.$scope.selectedArtifactId) {
122             return null;
123         }
124         let artifact:ArtifactModel = this.$scope.artifacts.filter((art) => {
125             return art.uniqueId == this.$scope.selectedArtifactId;
126         })[0];
127         return artifact;
128     }
129
130     private initScope = ():void => {
131         let self = this;
132         this.$scope.isLoading = false;
133         this.$scope.selectedArtifactId = null;
134         this.initDescriptions();
135         if(this.$scope.component.deploymentArtifacts) {
136             this.initArtifacts(false);
137         } else {
138             this.initArtifacts(true);
139         }
140         this.$scope.setValidState(true);
141
142         this.$scope.tableHeadersList = [
143             {title: 'Name', property: 'artifactDisplayName'},
144             {title: 'Type', property: 'artifactType'},
145             {title: 'Deployment timeout', property: 'timeout'},
146             {title: 'Version', property: 'artifactVersion'},
147             {title: 'UUID', property: 'artifactUUID'}
148         ];
149
150         this.$templateCache.put("deployment-artifacts-description-popover.html", require('app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-description-popover.html'));
151         this.$scope.popoverTemplate = "deployment-artifacts-description-popover.html";
152
153         this.$scope.isLicenseArtifact = (artifact:ArtifactModel):boolean => {
154             let isLicense:boolean = false;
155             if (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent()) {
156
157                 isLicense = this.artifactsUtils.isLicenseType(artifact.artifactType);
158             }
159
160             return isLicense;
161         };
162
163         this.$scope.sort = (sortBy:string):void => {
164             this.$scope.reverse = (this.$scope.sortBy === sortBy) ? !this.$scope.reverse : false;
165             this.$scope.sortBy = sortBy;
166         };
167
168         this.$scope.getValidationPattern = (validationType:string, parameterType?:string):RegExp => {
169             return this.validationUtils.getValidationPattern(validationType, parameterType);
170         };
171
172         this.$scope.validateJson = (json:string):boolean => {
173             if (!json) {
174                 return true;
175             }
176             return this.validationUtils.validateJson(json);
177         };
178
179         this.$scope.viewModeOrCsarComponent = ():boolean => {
180             return this.$scope.isViewMode() || (this.$scope.component.isResource() && (<Resource>this.$scope.component).isCsarComponent());
181         };
182
183         this.$scope.addOrUpdate = (artifact:ArtifactModel):void => {
184             artifact.artifactGroupType = 'DEPLOYMENT';
185             let artifactCopy = new ArtifactModel(artifact);
186
187             let success = (response:any):void => {
188                 this.$scope.artifactDescriptions[artifactCopy.artifactLabel] = artifactCopy.description;
189                 this.initArtifacts(true);
190                 //  this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
191             };
192
193             let error = (err:any):void => {
194                 console.log(err);
195                 this.initArtifacts(true);
196                 //  self.$scope.artifacts = _.values(self.$scope.component.deploymentArtifacts);
197             };
198
199             this.ModalsHandler.openArtifactModal(artifactCopy, this.$scope.component).then(success, error);
200         };
201
202         this.$scope.noArtifactsToShow = ():boolean => {
203             return !_.some(this.$scope.artifacts, 'esId');
204         };
205
206         this.$scope.resetValue = (parameter:any):void => {
207             if (!parameter.currentValue && parameter.defaultValue) {
208                 parameter.currentValue = parameter.defaultValue;
209             }
210             else if ('boolean' == parameter.type) {
211                 parameter.currentValue = parameter.currentValue.toUpperCase();
212             }
213         };
214
215         this.$scope.$watch('editForm.$valid', ():void => {
216             if (this.$scope.editForm) {
217                 //    this.$scope.setValidState(this.$scope.editForm.$valid);
218             }
219         });
220
221         this.$scope.updateSelectedArtifact = ():void => {
222             if (!this.$scope.isViewMode() && !this.$scope.isLoading) {
223                 let artifact:ArtifactModel = this.getCurrentArtifact();
224                 this.setArtifact(artifact); //resets artifact description to original value if invalid.
225                 if (artifact && artifact.originalDescription != artifact.description) {
226                     this.$scope.isLoading = true;
227                     let onSuccess = (responseArtifact:ArtifactModel):void => {
228                         this.$scope.artifactDescriptions[responseArtifact.artifactLabel] = responseArtifact.description;
229                         // this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
230                         this.initArtifacts(true);
231                         this.$scope.isLoading = false;
232                     };
233
234                     let onFailed = (error:any):void => {
235                         console.log('Delete artifact returned error:', error);
236                         this.$scope.isLoading = false;
237                     };
238
239                     this.$scope.component.addOrUpdateArtifact(artifact).then(onSuccess, onFailed);
240                 }
241             }
242         };
243
244         this.$scope.delete = (artifact:ArtifactModel):void => {
245             let onOk = ():void => {
246                 this.$scope.isLoading = true;
247                 let onSuccess = ():void => {
248                     this.$scope.isLoading = false;
249                     this.initArtifacts(true);
250                     //this.$scope.artifacts = _.values(this.$scope.component.deploymentArtifacts);
251                 };
252
253                 let onFailed = (error:any):void => {
254                     this.$scope.isLoading = false;
255                     console.log('Delete artifact returned error:', error);
256                 };
257
258                 this.$scope.component.deleteArtifact(artifact.uniqueId, artifact.artifactLabel).then(onSuccess, onFailed);
259             };
260
261             let title:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TITLE");
262             let message:string = self.$filter('translate')("ARTIFACT_VIEW_DELETE_MODAL_TEXT", "{'name': '" + artifact.artifactDisplayName + "'}");
263             this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
264         };
265
266         this.$scope.getEnvArtifactName = (artifact:ArtifactModel):string => {
267             let envArtifact = this.$scope.getEnvArtifact(artifact);
268             if (envArtifact) {
269                 return envArtifact.artifactDisplayName;
270             }
271         };
272
273         this.$scope.openEditEnvParametersModal = (artifact:ArtifactModel):void => {
274             this.ModalsHandler.openEditEnvParametersModal(artifact, this.$scope.component).then(()=> {
275                 this.initArtifacts(true);
276             }, ()=> {
277                 this.initArtifacts(true);
278             });
279         };
280
281         this.$scope.openDescriptionPopover = (artifactId:string):void => {
282             if (this.$scope.selectedArtifactId && this.$scope.selectedArtifactId != artifactId) {
283                 this.$scope.updateSelectedArtifact();
284             }
285             this.$scope.selectedArtifactId = artifactId;
286
287         };
288
289         this.$scope.closeDescriptionPopover = ():void => {
290             if (this.$scope.selectedArtifactId) {
291                 this.$scope.updateSelectedArtifact();
292                 this.$scope.selectedArtifactId = null;
293             }
294         };
295     };
296 }