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