Fix update the policy in SDC UI
[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 { PROPERTY_TYPES, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA } from "app/utils";
24 import { DataTypesService } from "app/services";
25 import { PropertyModel, DataTypesMap, Component, GroupInstance, PolicyInstance, PropertyBEModel, ComponentMetadata } 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, SdcUiServices, SdcUiComponents } 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
34 export interface IEditPropertyModel {
35     property:PropertyModel;
36     types:Array<string>;
37     simpleTypes:Array<string>;
38 }
39
40 interface IPropertyFormViewModelScope extends ng.IScope {
41     forms:any;
42     editForm:ng.IFormController;
43     footerButtons:Array<any>;
44     isNew:boolean;
45     isLoading:boolean;
46     isService:boolean;
47     validationPattern:RegExp;
48     propertyNameValidationPattern:RegExp;
49     commentValidationPattern:RegExp;
50     editPropertyModel:IEditPropertyModel;
51     modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;    
52     currentPropertyIndex:number;
53     isLastProperty:boolean;
54     myValue:any;
55     nonPrimitiveTypes:Array<string>;
56     dataTypes:DataTypesMap;
57     isTypeDataType:boolean;
58     maxLength:number;
59     isPropertyValueOwner:boolean;
60     isVnfConfiguration:boolean;
61     constraints:string[];
62
63     validateJson(json:string):boolean;
64     save(doNotCloseModal?:boolean):void;
65     getValidationPattern(type:string):RegExp;
66     validateIntRange(value:string):boolean;
67     close():void;
68     onValueChange():void;
69     onSchemaTypeChange():void;
70     onTypeChange(resetSchema:boolean):void;
71     showSchema():boolean;
72     delete(property:PropertyModel):void;
73     getPrev():void;
74     getNext():void;
75     isSimpleType(typeName:string):boolean;
76     getDefaultValue():any;
77 }
78
79 export class PropertyFormViewModel {
80
81     static '$inject' = [
82         '$scope',
83         'Sdc.Services.DataTypesService',
84         '$uibModalInstance',
85         'property',
86         'ValidationPattern',
87         'PropertyNameValidationPattern',
88         'CommentValidationPattern',
89         'ValidationUtils',
90         // 'component',
91         '$filter',
92         'ModalServiceSdcUI',
93         'filteredProperties',
94         '$timeout',
95         'isPropertyValueOwner',
96         'propertyOwnerType',
97         'propertyOwnerId',
98         'ComponentInstanceServiceNg2',
99         'TopologyTemplateService',
100         'CompositionService',
101         'workspaceService'
102     ];
103  
104     private formState:FormState;
105
106     constructor(private $scope:IPropertyFormViewModelScope,
107                 private DataTypesService:DataTypesService,
108                 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
109                 private property:PropertyModel,
110                 private ValidationPattern:RegExp,
111                 private PropertyNameValidationPattern:RegExp,
112                 private CommentValidationPattern:RegExp,
113                 private ValidationUtils:ValidationUtils,
114                 // private component:Component,
115                 private $filter:ng.IFilterService,
116                 private modalService:SdcUiServices.ModalService,
117                 private filteredProperties:Array<PropertyModel>,
118                 private $timeout:ng.ITimeoutService,
119                 private isPropertyValueOwner:boolean,
120                 private propertyOwnerType:string,
121                 private propertyOwnerId:string,
122                 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
123                 private topologyTemplateService: TopologyTemplateService,
124                 private compositionService: CompositionService,
125                 private workspaceService: WorkspaceService) {
126
127         this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
128
129         this.initScope();
130     }
131
132     private initResource = ():void => {
133         this.$scope.editPropertyModel.property = new PropertyModel(this.property);
134         this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
135         this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.value || this.$scope.editPropertyModel.property.defaultValue;
136         this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"]  : null;
137         
138         this.setMaxLength();
139
140     };
141
142     //init property add-ons labels that show up at the left side of the input.
143     private initAddOnLabels = () => {
144         if (this.$scope.editPropertyModel.property.name == 'network_role' && this.$scope.isService) {
145             //the server sends back the normalized name. Remove it (to prevent interference with validation) and set the addon label to the component name directly.
146             //Note: this cant be done in properties.ts because we dont have access to the component
147             if (this.$scope.editPropertyModel.property.value) {
148                 let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.workspaceService.metadata.normalizedName + '.', "gi"));
149                 this.$scope.editPropertyModel.property.value = splitProp.pop();
150             }
151             this.$scope.editPropertyModel.property.addOn = this.workspaceService.metadata.name;
152         }
153     }
154
155     private initForNotSimpleType = ():void => {
156         let property = this.$scope.editPropertyModel.property;
157         this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
158         if (property.type && this.$scope.editPropertyModel.simpleTypes.indexOf(property.type) == -1) {
159             if (!(property.value || property.defaultValue)) {
160                 switch (property.type) {
161                     case PROPERTY_TYPES.MAP:
162                         this.$scope.myValue = {'': null};
163                         break;
164                     case PROPERTY_TYPES.LIST:
165                         this.$scope.myValue = [];
166                         break;
167                     default:
168                         this.$scope.myValue = {};
169                 }
170             } else {
171                 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
172             }
173         }
174     };
175
176     private setMaxLength = ():void => {
177         switch (this.$scope.editPropertyModel.property.type) {
178             case PROPERTY_TYPES.MAP:
179             case PROPERTY_TYPES.LIST:
180                 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
181                     PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
182                     PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
183                 break;
184             case PROPERTY_TYPES.JSON:
185                 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
186                 break;
187             default:
188                 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
189         }
190     };
191
192
193     private initScope = ():void => {
194
195         //scope properties
196         this.$scope.forms = {};
197         this.$scope.validationPattern = this.ValidationPattern;
198         this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
199         this.$scope.commentValidationPattern = this.CommentValidationPattern;
200         this.$scope.isLoading = false;
201         this.$scope.isNew = (this.formState === FormState.CREATE);
202         this.$scope.isService = this.workspaceService.metadata.isService();
203         this.$scope.modalInstanceProperty = this.$uibModalInstance;
204         this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
205         this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
206         this.$scope.dataTypes = this.DataTypesService.getAllDataTypes();
207         this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
208         this.$scope.propertyOwnerType = this.propertyOwnerType;
209
210         this.$scope.editPropertyModel = {
211             property : new PropertyModel(this.property),
212             types : PROPERTY_DATA.TYPES,
213             simpleTypes : PROPERTY_DATA.SIMPLE_TYPES}; //All simple types
214
215
216         //check if property of VnfConfiguration
217         this.$scope.isVnfConfiguration = false;
218         if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
219
220             var componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
221                 return ci.uniqueId === this.property.resourceInstanceUniqueId;
222             });
223             if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
224                 this.$scope.isVnfConfiguration = true;
225             }
226         }
227
228         this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
229             return this.$scope.editPropertyModel.types.indexOf(type) == -1;
230         });
231         this.initResource();
232         this.initForNotSimpleType();
233
234
235         this.$scope.validateJson = (json:string):boolean => {
236             if (!json) {
237                 return true;
238             }
239             return this.ValidationUtils.validateJson(json);
240         };
241
242
243         //scope methods
244         this.$scope.save = (doNotCloseModal?:boolean):void => {
245             let property:PropertyModel = this.$scope.editPropertyModel.property;
246             this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
247             //if read only - or no changes made - just closes the modal
248             //need to check for property.value changes manually to detect if map properties deleted
249             if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
250                 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
251                 this.$uibModalInstance.close();
252                 return;
253             }
254
255             this.$scope.isLoading = true;
256
257             let onPropertyFaild = (response):void => {
258                 console.info('onFaild', response);
259                 this.$scope.isLoading = false;
260             };
261
262             let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
263                 console.info('onPropertyResourceSuccess : ', propertyFromBE);
264                 this.$scope.isLoading = false;
265                 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
266                 if (!doNotCloseModal) {
267                     this.$uibModalInstance.close(propertyFromBE);
268                 } else {
269                     this.$scope.forms.editForm.$setPristine();
270                     this.$scope.editPropertyModel.property = new PropertyModel();
271                 }
272             };
273
274             //Not clean, but doing this as a temporary fix until we update the property right panel modals
275             if (this.propertyOwnerType === "group"){
276                 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
277                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFaild(error));
278             } else if (this.propertyOwnerType === "policy"){
279                 if (!this.$scope.editPropertyModel.property.simpleType &&
280                     !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
281                     !_.isNil(this.$scope.myValue)) {
282                     property.value = JSON.stringify(this.$scope.myValue);
283                 }
284                 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
285                     .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFaild(error));
286             } else {
287                 //in case we have uniqueId we call update method
288                 if (this.$scope.isPropertyValueOwner) {
289                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
290                         let myValueString:string = JSON.stringify(this.$scope.myValue);
291                         property.value = myValueString;
292                     }
293                     this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]), onPropertyFaild);
294                 } else {
295                     if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
296                         let myValueString:string = JSON.stringify(this.$scope.myValue);
297                         property.defaultValue = myValueString;
298                     } else {
299                         this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
300                     }
301                     this.addOrUpdateProperty(property).subscribe(onPropertySuccess, onPropertyFaild);
302                 }
303             }
304         };
305
306         this.$scope.getPrev = ():void=> {
307             this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
308             this.initResource();
309             this.initForNotSimpleType();
310             this.$scope.isLastProperty = false;
311         };
312
313         this.$scope.getNext = ():void=> {
314             this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
315             this.initResource();
316             this.initForNotSimpleType();
317             this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
318         };
319
320         this.$scope.isSimpleType = (typeName:string):boolean=> {
321             return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
322         };
323
324         this.$scope.showSchema = ():boolean => {
325             return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
326         };
327
328         this.$scope.getValidationPattern = (type:string):RegExp => {
329             return this.ValidationUtils.getValidationPattern(type);
330         };
331
332         this.$scope.validateIntRange = (value:string):boolean => {
333             return !value || this.ValidationUtils.validateIntRange(value);
334         };
335
336         this.$scope.close = ():void => {
337             this.$uibModalInstance.close();
338         };
339
340         // put default value when instance value is empty
341         this.$scope.onValueChange = ():void => {
342             if (!this.$scope.editPropertyModel.property.value) {
343                 if (this.$scope.isPropertyValueOwner) {
344                     this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
345                 }
346             }
347         };
348
349         // Add the done button at the footer.
350         this.$scope.footerButtons = [
351             {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
352             {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
353         ];
354
355         this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
356             this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
357         });
358
359         this.$scope.getDefaultValue = ():any => {
360             return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
361         };
362
363         this.$scope.onTypeChange = ():void => {
364             this.$scope.editPropertyModel.property.value = '';
365             this.$scope.editPropertyModel.property.defaultValue = '';
366             this.setMaxLength();
367             this.initForNotSimpleType();
368         };
369
370         this.$scope.onSchemaTypeChange = ():void => {
371             if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
372                 this.$scope.myValue = {'': null};
373             } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
374                 this.$scope.myValue = [];
375             }
376             this.setMaxLength();
377         };
378
379         this.$scope.delete = (property:PropertyModel):void => {
380             let onOk: Function = ():void => {
381                 this.deleteProperty(property.uniqueId).subscribe(
382                     this.$scope.close
383                 );
384             };
385             let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
386             let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
387             const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
388             this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
389         };
390     }
391
392     private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
393
394         return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
395             .map(newProperties => {
396                 newProperties.forEach((newProperty) => {
397                     if(newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
398                     // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
399                     let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
400                         uniqueId: newProperty.uniqueId,
401                         path: newProperty.path
402                     });
403                     let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
404                     this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
405                 });
406                 return newProperties;
407             });
408     };
409
410     private addOrUpdateProperty = (property:PropertyModel):Observable<PropertyModel> => {
411         if (!property.uniqueId) {
412             let onSuccess = (property:PropertyModel):PropertyModel => {
413                 let newProperty = new PropertyModel(property);
414                 this.filteredProperties.push(newProperty);
415                 return newProperty;
416             };
417             return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
418         }
419         else {
420             let onSuccess = (newProperty:PropertyModel):PropertyModel => {
421                 // find exist instance property in parent component for update the new value ( find bu uniqueId )
422                 let existProperty:PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
423                 let propertyIndex = this.filteredProperties.indexOf(existProperty);
424                 this.filteredProperties[propertyIndex] = newProperty;
425                 return newProperty;
426             };
427             return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
428         }
429     };
430
431     public deleteProperty = (propertyId:string):Observable<void> => {
432         let onSuccess = ():void => {
433             console.log("Property deleted");
434             delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
435         };
436         let onFailed = ():void => {
437             console.log("Failed to delete property");
438         };
439         return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);
440     };
441 }