2741c464c860b462e4497888645a0050bf80b122
[sdc.git] / catalog-ui / src / app / view-models / forms / property-forms / component-property-form / property-form-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 * as _ from "lodash";
23 import {FormState, PROPERTY_DATA, PROPERTY_TYPES, PROPERTY_VALUE_CONSTRAINTS, ValidationUtils} from "app/utils";
24 import {DataTypesService} from "app/services";
25 import {DataTypesMap, PropertyModel} from "app/models";
26 import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
27 import {ComponentInstanceServiceNg2} from "app/ng2/services/component-instance-services/component-instance.service";
28 import {SdcUiCommon, SdcUiComponents, SdcUiServices} from "onap-ui-angular";
29 import {CompositionService} from "app/ng2/pages/composition/composition.service";
30 import {WorkspaceService} from "app/ng2/pages/workspace/workspace.service";
31 import {Observable} from "rxjs";
32 import {TopologyTemplateService} from "app/ng2/services/component-services/topology-template.service";
33 import {InstanceFeDetails} from "../../../../models/instance-fe-details";
34 import {ToscaGetFunction} from "../../../../models/tosca-get-function";
35
36 export interface IEditPropertyModel {
37     property:PropertyModel;
38     types:Array<string>;
39     simpleTypes:Array<string>;
40     hasGetFunctionValue: boolean;
41     isGetFunctionValid: boolean;
42 }
43
44 interface IPropertyFormViewModelScope extends ng.IScope {
45     forms:any;
46     editForm:ng.IFormController;
47     footerButtons:Array<any>;
48     isNew:boolean;
49     isLoading:boolean;
50     componentMetadata: { isService: boolean, isVfc: boolean }
51     validationPattern:RegExp;
52     propertyNameValidationPattern:RegExp;
53     commentValidationPattern:RegExp;
54     editPropertyModel: IEditPropertyModel;
55     componentInstanceMap: Map<string, InstanceFeDetails>;
56     modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
57     currentPropertyIndex:number;
58     isLastProperty:boolean;
59     myValue:any;
60     nonPrimitiveTypes:Array<string>;
61     dataTypes:DataTypesMap;
62     isTypeDataType:boolean;
63     maxLength:number;
64     isPropertyValueOwner:boolean;
65     isVnfConfiguration:boolean;
66     constraints:string[];
67     modelNameFilter:string;
68     isGetFunctionValueType: boolean;
69
70     validateJson(json:string):boolean;
71     save(doNotCloseModal?:boolean):void;
72     getValidationPattern(type:string):RegExp;
73     validateIntRange(value:string):boolean;
74     close():void;
75     onValueChange():void;
76     onSchemaTypeChange():void;
77     onTypeChange(resetSchema:boolean):void;
78     showSchema():boolean;
79     delete(property:PropertyModel):void;
80     getPrev():void;
81     getNext():void;
82     isSimpleType(typeName:string):boolean;
83     getDefaultValue():any;
84     onValueTypeChange(): void;
85 }
86
87 export class PropertyFormViewModel {
88
89     static '$inject' = [
90         '$scope',
91         'Sdc.Services.DataTypesService',
92         '$uibModalInstance',
93         'property',
94         'ValidationPattern',
95         'PropertyNameValidationPattern',
96         'CommentValidationPattern',
97         'ValidationUtils',
98         // 'component',
99         '$filter',
100         'ModalServiceSdcUI',
101         'filteredProperties',
102         '$timeout',
103         'isPropertyValueOwner',
104         'propertyOwnerType',
105         'propertyOwnerId',
106         'ComponentInstanceServiceNg2',
107         'TopologyTemplateService',
108         'CompositionService',
109         'workspaceService'
110     ];
111
112     private formState:FormState;
113
114     constructor(private $scope:IPropertyFormViewModelScope,
115                 private DataTypesService:DataTypesService,
116                 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
117                 private property:PropertyModel,
118                 private ValidationPattern:RegExp,
119                 private PropertyNameValidationPattern:RegExp,
120                 private CommentValidationPattern:RegExp,
121                 private ValidationUtils:ValidationUtils,
122                 // private component:Component,
123                 private $filter:ng.IFilterService,
124                 private modalService:SdcUiServices.ModalService,
125                 private filteredProperties:Array<PropertyModel>,
126                 private $timeout:ng.ITimeoutService,
127                 private isPropertyValueOwner:boolean,
128                 private propertyOwnerType:string,
129                 private propertyOwnerId:string,
130                 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
131                 private topologyTemplateService: TopologyTemplateService,
132                 private compositionService: CompositionService,
133                 private workspaceService: WorkspaceService) {
134
135         this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
136         this.initScope();
137     }
138
139     private initResource = ():void => {
140         this.$scope.editPropertyModel.property = new PropertyModel(this.property);
141         this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
142         this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.value || this.$scope.editPropertyModel.property.defaultValue;
143         this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"]  : null;
144         this.initToscaGetFunction();
145         this.setMaxLength();
146     };
147
148     private initToscaGetFunction() {
149         this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaGetFunction();
150         this.$scope.editPropertyModel.isGetFunctionValid = true;
151     }
152
153     private initForNotSimpleType = ():void => {
154         const property = this.$scope.editPropertyModel.property;
155         this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
156         if (property.isToscaGetFunction()) {
157             this.initValueForGetFunction();
158             return;
159         }
160
161         if (this.isComplexType(property.type)) {
162             if (property.value || property.defaultValue) {
163                 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
164             } else {
165                 this.initEmptyComplexValue(property.type);
166             }
167         }
168     };
169
170     private initValueForGetFunction(): void {
171         const property = this.$scope.editPropertyModel.property;
172         if (property.defaultValue) {
173             this.$scope.myValue = JSON.parse(property.defaultValue);
174             return;
175         }
176         if (this.isComplexType(property.type)) {
177             this.initEmptyComplexValue(property.type);
178             return;
179         }
180
181         this.$scope.myValue = undefined;
182     }
183
184     private initComponentInstanceMap() {
185         this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
186         if (this.compositionService.componentInstances) {
187             this.compositionService.componentInstances.forEach(value => {
188                 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
189                     name: value.name
190                 });
191             });
192         }
193     }
194
195     private initEmptyComplexValue(type: string): any {
196         switch (type) {
197             case PROPERTY_TYPES.MAP:
198                 this.$scope.myValue = {'': null};
199                 break;
200             case PROPERTY_TYPES.LIST:
201                 this.$scope.myValue = [];
202                 break;
203             default:
204                 this.$scope.myValue = {};
205         }
206     }
207
208     private isComplexType(type: string): boolean {
209         if (!type) {
210             return false;
211         }
212         return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
213     }
214
215     private setMaxLength = ():void => {
216         switch (this.$scope.editPropertyModel.property.type) {
217             case PROPERTY_TYPES.MAP:
218             case PROPERTY_TYPES.LIST:
219                 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
220                     PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
221                     PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
222                 break;
223             case PROPERTY_TYPES.JSON:
224                 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
225                 break;
226             default:
227                 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
228         }
229     };
230
231
232     private initScope = ():void => {
233
234         //scope properties
235         this.$scope.isLoading = true;
236         this.$scope.forms = {};
237         this.$scope.validationPattern = this.ValidationPattern;
238         this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
239         this.$scope.commentValidationPattern = this.CommentValidationPattern;
240         this.$scope.isNew = (this.formState === FormState.CREATE);
241         this.$scope.componentMetadata = {
242             isService: this.workspaceService.metadata.isService(),
243             isVfc: this.workspaceService.metadata.isVfc()
244         }
245         this.$scope.modalInstanceProperty = this.$uibModalInstance;
246         this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
247         this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
248         const property = new PropertyModel(this.property);
249         this.$scope.editPropertyModel = {
250             'property': property,
251             types: PROPERTY_DATA.TYPES,
252             simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
253             hasGetFunctionValue: property.isToscaGetFunction(),
254             isGetFunctionValid: true,
255         };
256         this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
257         this.$scope.propertyOwnerType = this.propertyOwnerType;
258         this.$scope.modelNameFilter = this.workspaceService.metadata.model;
259         //check if property of VnfConfiguration
260         this.$scope.isVnfConfiguration = false;
261         if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
262             const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
263                 return ci.uniqueId === this.property.resourceInstanceUniqueId;
264             });
265             if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
266                 this.$scope.isVnfConfiguration = true;
267             }
268         }
269         this.initResource();
270         this.initForNotSimpleType();
271         this.initComponentInstanceMap();
272
273         this.$scope.validateJson = (json:string):boolean => {
274             if (!json) {
275                 return true;
276             }
277             return this.ValidationUtils.validateJson(json);
278         };
279
280         this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
281             this.$scope.dataTypes = response.data as DataTypesMap;
282             this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
283                 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
284             });
285
286             this.$scope.isLoading = false;
287         });
288
289         //scope methods
290         this.$scope.save = (doNotCloseModal?:boolean):void => {
291             let property:PropertyModel = this.$scope.editPropertyModel.property;
292             this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
293             //if read only - or no changes made - just closes the modal
294             //need to check for property.value changes manually to detect if map properties deleted
295             if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
296                 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
297                 this.$uibModalInstance.close();
298                 return;
299             }
300
301             this.$scope.isLoading = true;
302
303             let onPropertyFailure = (response):void => {
304                 console.error('Failed to update property', response);
305                 this.$scope.isLoading = false;
306             };
307
308             let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
309                 this.$scope.isLoading = false;
310                 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
311                 if (!doNotCloseModal) {
312                     this.$uibModalInstance.close(propertyFromBE);
313                 } else {
314                     this.$scope.forms.editForm.$setPristine();
315                     this.$scope.editPropertyModel.property = new PropertyModel();
316                 }
317             };
318
319             //Not clean, but doing this as a temporary fix until we update the property right panel modals
320             if (this.propertyOwnerType === "group"){
321                 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
322                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
323             } else if (this.propertyOwnerType === "policy"){
324                 if (!this.$scope.editPropertyModel.property.simpleType &&
325                     !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
326                     !_.isNil(this.$scope.myValue)) {
327                     property.value = JSON.stringify(this.$scope.myValue);
328                 }
329                 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
330                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
331             } else {
332                 //in case we have uniqueId we call update method
333                 if (this.$scope.isPropertyValueOwner) {
334                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
335                         property.value = JSON.stringify(this.$scope.myValue);
336                     }
337                     this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
338                         error => onPropertyFailure(error));
339                 } else {
340                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
341                         property.defaultValue = JSON.stringify(this.$scope.myValue);
342                     } else {
343                         this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
344                     }
345                     this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
346                 }
347             }
348         };
349
350         this.$scope.getPrev = ():void=> {
351             this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
352             this.initResource();
353             this.initForNotSimpleType();
354             this.$scope.isLastProperty = false;
355         };
356
357         this.$scope.getNext = ():void=> {
358             this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
359             this.initResource();
360             this.initForNotSimpleType();
361             this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
362         };
363
364         this.$scope.isSimpleType = (typeName:string):boolean=> {
365             return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
366         };
367
368         this.$scope.showSchema = ():boolean => {
369             return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
370         };
371
372         this.$scope.getValidationPattern = (type:string):RegExp => {
373             return this.ValidationUtils.getValidationPattern(type);
374         };
375
376         this.$scope.validateIntRange = (value:string):boolean => {
377             return !value || this.ValidationUtils.validateIntRange(value);
378         };
379
380         this.$scope.close = ():void => {
381             this.$uibModalInstance.close();
382         };
383
384         // put default value when instance value is empty
385         this.$scope.onValueChange = ():void => {
386             if (!this.$scope.editPropertyModel.property.value) {
387                 if (this.$scope.isPropertyValueOwner) {
388                     this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
389                 }
390             }
391         };
392
393         // Add the done button at the footer.
394         this.$scope.footerButtons = [
395             {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
396             {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
397         ];
398
399         this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
400             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
401                 this.$scope.footerButtons[0].disabled = newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
402             } else {
403                 this.$scope.footerButtons[0].disabled = newVal;
404             }
405         });
406
407         this.$scope.$watch("forms.editForm.$valid", (newVal) => {
408             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
409                 this.$scope.footerButtons[0].disabled = !newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
410             } else {
411                 this.$scope.footerButtons[0].disabled = !newVal;
412             }
413         });
414
415         this.$scope.getDefaultValue = ():any => {
416             return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
417         };
418
419         this.$scope.onTypeChange = ():void => {
420             this.$scope.editPropertyModel.property.value = '';
421             this.$scope.editPropertyModel.property.defaultValue = '';
422             this.setMaxLength();
423             this.initForNotSimpleType();
424         };
425
426         this.$scope.onSchemaTypeChange = ():void => {
427             if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
428                 this.$scope.myValue = {'': null};
429             } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
430                 this.$scope.myValue = [];
431             }
432             this.setMaxLength();
433         };
434
435         this.$scope.delete = (property:PropertyModel):void => {
436             let onOk: Function = ():void => {
437                 this.deleteProperty(property.uniqueId).subscribe(
438                     this.$scope.close
439                 );
440             };
441             let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
442             let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
443             const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
444             this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
445         };
446
447         this.$scope.onValueTypeChange = (): void => {
448             this.setEmptyValue();
449             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
450                 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
451             } else {
452                 this.$scope.editPropertyModel.property.toscaGetFunction = undefined;
453                 this.$scope.editPropertyModel.isGetFunctionValid = true;
454             }
455         }
456
457         this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
458             this.$scope.editPropertyModel.property.toscaGetFunction = toscaGetFunction;
459         }
460
461         this.$scope.onGetFunctionValidityChange = (isValid: boolean): void => {
462             if (isValid) {
463                 this.$scope.editPropertyModel.isGetFunctionValid = true;
464                 return;
465             }
466             this.$scope.editPropertyModel.isGetFunctionValid = undefined;
467         }
468
469     };
470
471     private setEmptyValue() {
472         const property1 = this.$scope.editPropertyModel.property;
473         property1.value = undefined;
474         if (this.isComplexType(property1.type)) {
475             this.initEmptyComplexValue(property1.type);
476             return;
477         }
478         this.$scope.myValue = '';
479     }
480
481     private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
482
483         return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
484             .map(newProperties => {
485                 newProperties.forEach((newProperty) => {
486                     if (!_.isNil(newProperty.path)) {
487                         if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
488                         // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
489                         let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
490                             uniqueId: newProperty.uniqueId,
491                             path: newProperty.path
492                         });
493                         let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
494                         this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
495                     }
496                 });
497                 return newProperties;
498             });
499     };
500
501     private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
502         if (!property.uniqueId) {
503             let onSuccess = (newProperty: PropertyModel): PropertyModel => {
504                 this.filteredProperties.push(newProperty);
505                 return newProperty;
506             };
507             return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
508                 .map(onSuccess);
509         } else {
510             let onSuccess = (newProperty: PropertyModel): PropertyModel => {
511                 // find exist instance property in parent component for update the new value ( find bu uniqueId )
512                 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
513                 let propertyIndex = this.filteredProperties.indexOf(existProperty);
514                 this.filteredProperties[propertyIndex] = newProperty;
515                 return newProperty;
516             };
517             return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
518         }
519     };
520
521     public deleteProperty = (propertyId:string):Observable<void> => {
522         let onSuccess = ():void => {
523             console.debug("Property deleted");
524             delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
525         };
526         let onFailed = ():void => {
527             console.debug("Failed to delete property");
528         };
529         return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);
530     };
531
532 }