Fix VFC map or list property update
[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.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
143         this.initToscaGetFunction();
144         this.setMaxLength();
145     };
146
147     private initToscaGetFunction() {
148         this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaGetFunction();
149         this.$scope.editPropertyModel.isGetFunctionValid = true;
150     }
151
152     private initForNotSimpleType = ():void => {
153         const property = this.$scope.editPropertyModel.property;
154         this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
155         if (property.isToscaGetFunction()) {
156             this.initValueForGetFunction();
157             return;
158         }
159
160         if (this.isComplexType(property.type)) {
161             if (property.value || property.defaultValue) {
162                 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
163             } else {
164                 this.initEmptyComplexValue(property.type);
165             }
166         }
167     };
168
169     private initValueForGetFunction(): void {
170         const property = this.$scope.editPropertyModel.property;
171         if (property.defaultValue) {
172             this.$scope.myValue = JSON.parse(property.defaultValue);
173             return;
174         }
175         if (this.isComplexType(property.type)) {
176             this.initEmptyComplexValue(property.type);
177             return;
178         }
179
180         this.$scope.myValue = undefined;
181     }
182
183     private initComponentInstanceMap() {
184         this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
185         if (this.compositionService.componentInstances) {
186             this.compositionService.componentInstances.forEach(value => {
187                 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
188                     name: value.name
189                 });
190             });
191         }
192     }
193
194     private initEmptyComplexValue(type: string): any {
195         switch (type) {
196             case PROPERTY_TYPES.MAP:
197                 this.$scope.myValue = {'': null};
198                 break;
199             case PROPERTY_TYPES.LIST:
200                 this.$scope.myValue = [];
201                 break;
202             default:
203                 this.$scope.myValue = {};
204         }
205     }
206
207     private isComplexType(type: string): boolean {
208         if (!type) {
209             return false;
210         }
211         return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
212     }
213
214     private setMaxLength = ():void => {
215         switch (this.$scope.editPropertyModel.property.type) {
216             case PROPERTY_TYPES.MAP:
217             case PROPERTY_TYPES.LIST:
218                 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
219                     PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
220                     PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
221                 break;
222             case PROPERTY_TYPES.JSON:
223                 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
224                 break;
225             default:
226                 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
227         }
228     };
229
230
231     private initScope = ():void => {
232
233         //scope properties
234         this.$scope.isLoading = true;
235         this.$scope.forms = {};
236         this.$scope.validationPattern = this.ValidationPattern;
237         this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
238         this.$scope.commentValidationPattern = this.CommentValidationPattern;
239         this.$scope.isNew = (this.formState === FormState.CREATE);
240         this.$scope.componentMetadata = {
241             isService: this.workspaceService.metadata.isService(),
242             isVfc: this.workspaceService.metadata.isVfc()
243         }
244         this.$scope.modalInstanceProperty = this.$uibModalInstance;
245         this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
246         this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
247         const property = new PropertyModel(this.property);
248         this.$scope.editPropertyModel = {
249             'property': property,
250             types: PROPERTY_DATA.TYPES,
251             simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
252             hasGetFunctionValue: property.isToscaGetFunction(),
253             isGetFunctionValid: true,
254         };
255         this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
256         this.$scope.propertyOwnerType = this.propertyOwnerType;
257         this.$scope.modelNameFilter = this.workspaceService.metadata.model;
258         //check if property of VnfConfiguration
259         this.$scope.isVnfConfiguration = false;
260         if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
261             const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
262                 return ci.uniqueId === this.property.resourceInstanceUniqueId;
263             });
264             if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
265                 this.$scope.isVnfConfiguration = true;
266             }
267         }
268         this.initResource();
269         this.initForNotSimpleType();
270         this.initComponentInstanceMap();
271
272         this.$scope.validateJson = (json:string):boolean => {
273             if (!json) {
274                 return true;
275             }
276             return this.ValidationUtils.validateJson(json);
277         };
278
279         this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
280             this.$scope.dataTypes = response.data as DataTypesMap;
281             this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
282                 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
283             });
284
285             this.$scope.isLoading = false;
286         });
287
288         //scope methods
289         this.$scope.save = (doNotCloseModal?:boolean):void => {
290             let property:PropertyModel = this.$scope.editPropertyModel.property;
291             this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
292             //if read only - or no changes made - just closes the modal
293             //need to check for property.value changes manually to detect if map properties deleted
294             if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
295                 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
296                 this.$uibModalInstance.close();
297                 return;
298             }
299
300             this.$scope.isLoading = true;
301
302             let onPropertyFailure = (response):void => {
303                 console.error('Failed to update property', response);
304                 this.$scope.isLoading = false;
305             };
306
307             let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
308                 this.$scope.isLoading = false;
309                 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
310                 if (!doNotCloseModal) {
311                     this.$uibModalInstance.close(propertyFromBE);
312                 } else {
313                     this.$scope.forms.editForm.$setPristine();
314                     this.$scope.editPropertyModel.property = new PropertyModel();
315                 }
316             };
317
318             //Not clean, but doing this as a temporary fix until we update the property right panel modals
319             if (this.propertyOwnerType === "group"){
320                 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
321                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
322             } else if (this.propertyOwnerType === "policy"){
323                 if (!this.$scope.editPropertyModel.property.simpleType &&
324                     !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
325                     !_.isNil(this.$scope.myValue)) {
326                     property.value = JSON.stringify(this.$scope.myValue);
327                 }
328                 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
329                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
330             } else {
331                 //in case we have uniqueId we call update method
332                 if (this.$scope.isPropertyValueOwner) {
333                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
334                         property.value = JSON.stringify(this.$scope.myValue);
335                     }
336                     this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
337                         error => onPropertyFailure(error));
338                 } else {
339                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
340                         property.defaultValue = JSON.stringify(this.$scope.myValue);
341                     } else {
342                         this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
343                     }
344                     this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
345                 }
346             }
347         };
348
349         this.$scope.getPrev = ():void=> {
350             this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
351             this.initResource();
352             this.initForNotSimpleType();
353             this.$scope.isLastProperty = false;
354         };
355
356         this.$scope.getNext = ():void=> {
357             this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
358             this.initResource();
359             this.initForNotSimpleType();
360             this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
361         };
362
363         this.$scope.isSimpleType = (typeName:string):boolean=> {
364             return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
365         };
366
367         this.$scope.showSchema = ():boolean => {
368             return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
369         };
370
371         this.$scope.getValidationPattern = (type:string):RegExp => {
372             return this.ValidationUtils.getValidationPattern(type);
373         };
374
375         this.$scope.validateIntRange = (value:string):boolean => {
376             return !value || this.ValidationUtils.validateIntRange(value);
377         };
378
379         this.$scope.close = ():void => {
380             this.$uibModalInstance.close();
381         };
382
383         // put default value when instance value is empty
384         this.$scope.onValueChange = ():void => {
385             if (!this.$scope.editPropertyModel.property.value) {
386                 if (this.$scope.isPropertyValueOwner) {
387                     this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
388                 }
389             }
390         };
391
392         // Add the done button at the footer.
393         this.$scope.footerButtons = [
394             {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
395             {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
396         ];
397
398         this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
399             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
400                 this.$scope.footerButtons[0].disabled = newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
401             } else {
402                 this.$scope.footerButtons[0].disabled = newVal;
403             }
404         });
405
406         this.$scope.$watch("forms.editForm.$valid", (newVal) => {
407             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
408                 this.$scope.footerButtons[0].disabled = !newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
409             } else {
410                 this.$scope.footerButtons[0].disabled = !newVal;
411             }
412         });
413
414         this.$scope.getDefaultValue = ():any => {
415             return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
416         };
417
418         this.$scope.onTypeChange = ():void => {
419             this.$scope.editPropertyModel.property.value = '';
420             this.$scope.editPropertyModel.property.defaultValue = '';
421             this.setMaxLength();
422             this.initForNotSimpleType();
423         };
424
425         this.$scope.onSchemaTypeChange = ():void => {
426             if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
427                 this.$scope.myValue = {'': null};
428             } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
429                 this.$scope.myValue = [];
430             }
431             this.setMaxLength();
432         };
433
434         this.$scope.delete = (property:PropertyModel):void => {
435             let onOk: Function = ():void => {
436                 this.deleteProperty(property.uniqueId).subscribe(
437                     this.$scope.close
438                 );
439             };
440             let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
441             let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
442             const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
443             this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
444         };
445
446         this.$scope.onValueTypeChange = (): void => {
447             this.setEmptyValue();
448             if (this.$scope.editPropertyModel.hasGetFunctionValue) {
449                 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
450             } else {
451                 this.$scope.editPropertyModel.property.toscaGetFunction = undefined;
452                 this.$scope.editPropertyModel.isGetFunctionValid = true;
453             }
454         }
455
456         this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
457             this.$scope.editPropertyModel.property.toscaGetFunction = toscaGetFunction;
458         }
459
460         this.$scope.onGetFunctionValidityChange = (isValid: boolean): void => {
461             if (isValid) {
462                 this.$scope.editPropertyModel.isGetFunctionValid = true;
463                 return;
464             }
465             this.$scope.editPropertyModel.isGetFunctionValid = undefined;
466         }
467
468     };
469
470     private setEmptyValue() {
471         const property1 = this.$scope.editPropertyModel.property;
472         property1.value = undefined;
473         if (this.isComplexType(property1.type)) {
474             this.initEmptyComplexValue(property1.type);
475             return;
476         }
477         this.$scope.myValue = '';
478     }
479
480     private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
481
482         return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
483             .map(newProperties => {
484                 newProperties.forEach((newProperty) => {
485                     if (!_.isNil(newProperty.path)) {
486                         if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
487                         // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
488                         let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
489                             uniqueId: newProperty.uniqueId,
490                             path: newProperty.path
491                         });
492                         let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
493                         this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
494                     }
495                 });
496                 return newProperties;
497             });
498     };
499
500     private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
501         if (!property.uniqueId) {
502             let onSuccess = (newProperty: PropertyModel): PropertyModel => {
503                 this.filteredProperties.push(newProperty);
504                 return newProperty;
505             };
506             return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
507                 .map(onSuccess);
508         } else {
509             let onSuccess = (newProperty: PropertyModel): PropertyModel => {
510                 // find exist instance property in parent component for update the new value ( find bu uniqueId )
511                 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
512                 let propertyIndex = this.filteredProperties.indexOf(existProperty);
513                 this.filteredProperties[propertyIndex] = newProperty;
514                 return newProperty;
515             };
516             return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
517         }
518     };
519
520     public deleteProperty = (propertyId:string):Observable<void> => {
521         let onSuccess = ():void => {
522             console.debug("Property deleted");
523             delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
524         };
525         let onFailed = ():void => {
526             console.debug("Failed to delete property");
527         };
528         return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);
529     };
530
531 }