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