ee2e94f9341b4ade2a9ded36f0659a6b750b5c66
[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 {
23     PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils";
24 import {DataTypesService} from "app/services";
25 import {PropertyModel, DataTypesMap, Component} from "app/models";
26 import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
27
28 export interface IEditPropertyModel {
29     property:PropertyModel;
30     types:Array<string>;
31     simpleTypes:Array<string>;
32 }
33
34 interface IPropertyFormViewModelScope extends ng.IScope {
35     forms:any;
36     editForm:ng.IFormController;
37     footerButtons:Array<any>;
38     isNew:boolean;
39     isLoading:boolean;
40     isService:boolean;
41     validationPattern:RegExp;
42     propertyNameValidationPattern:RegExp;
43     commentValidationPattern:RegExp;
44     editPropertyModel:IEditPropertyModel;
45     modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
46     currentPropertyIndex:number;
47     isLastProperty:boolean;
48     myValue:any;
49     nonPrimitiveTypes:Array<string>;
50     dataTypes:DataTypesMap;
51     isTypeDataType:boolean;
52     maxLength:number;
53     isPropertyValueOwner:boolean;
54     isVnfConfiguration:boolean;
55
56     validateJson(json:string):boolean;
57     save(doNotCloseModal?:boolean):void;
58     getValidationPattern(type:string):RegExp;
59     validateIntRange(value:string):boolean;
60     close():void;
61     onValueChange():void;
62     onSchemaTypeChange():void;
63     onTypeChange(resetSchema:boolean):void;
64     showSchema():boolean;
65     delete(property:PropertyModel):void;
66     getPrev():void;
67     getNext():void;
68     isSimpleType(typeName:string):boolean;
69     getDefaultValue():any;
70 }
71
72 export class PropertyFormViewModel {
73
74     static '$inject' = [
75         '$scope',
76         'Sdc.Services.DataTypesService',
77         '$uibModalInstance',
78         'property',
79         'ValidationPattern',
80         'PropertyNameValidationPattern',
81         'CommentValidationPattern',
82         'ValidationUtils',
83         'component',
84         '$filter',
85         'ModalsHandler',
86         'filteredProperties',
87         '$timeout',
88         'isPropertyValueOwner'
89     ];
90
91     private formState:FormState;
92
93     constructor(private $scope:IPropertyFormViewModelScope,
94                 private DataTypesService:DataTypesService,
95                 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
96                 private property:PropertyModel,
97                 private ValidationPattern:RegExp,
98                 private PropertyNameValidationPattern:RegExp,
99                 private CommentValidationPattern:RegExp,
100                 private ValidationUtils:ValidationUtils,
101                 private component:Component,
102                 private $filter:ng.IFilterService,
103                 private ModalsHandler:ModalsHandler,
104                 private filteredProperties:Array<PropertyModel>,
105                 private $timeout:ng.ITimeoutService,
106                 private isPropertyValueOwner:boolean) {
107
108         this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
109         this.initScope();
110     }
111
112     private initResource = ():void => {
113         this.$scope.editPropertyModel.property = new PropertyModel(this.property);
114         this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
115         this.setMaxLength();
116         this.initAddOnLabels();
117     };
118
119     //init property add-ons labels that show up at the left side of the input.
120     private initAddOnLabels = () => {
121         if (this.$scope.editPropertyModel.property.name == 'network_role' && this.$scope.isService) {
122             //the server sends back the normalized name. Remove it (to prevent interference with validation) and set the addon label to the component name directly.
123             //Note: this cant be done in properties.ts because we dont have access to the component
124             if (this.$scope.editPropertyModel.property.value) {
125                 let splitProp = this.$scope.editPropertyModel.property.value.split(new RegExp(this.component.normalizedName + '.', "gi"));
126                 this.$scope.editPropertyModel.property.value = splitProp.pop();
127             }
128             this.$scope.editPropertyModel.property.addOn = this.component.name;
129         }
130     }
131
132     private initEditPropertyModel = ():void => {
133         this.$scope.editPropertyModel = {
134             property: null,
135             types: PROPERTY_DATA.TYPES,
136             simpleTypes: PROPERTY_DATA.SIMPLE_TYPES
137         };
138
139         this.initResource();
140     };
141
142     private initForNotSimpleType = ():void => {
143         let property = this.$scope.editPropertyModel.property;
144         this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
145         if (property.type && this.$scope.editPropertyModel.simpleTypes.indexOf(property.type) == -1) {
146             if (!(property.value || property.defaultValue)) {
147                 switch (property.type) {
148                     case PROPERTY_TYPES.MAP:
149                         this.$scope.myValue = {'': null};
150                         break;
151                     case PROPERTY_TYPES.LIST:
152                         this.$scope.myValue = [];
153                         break;
154                     default:
155                         this.$scope.myValue = {};
156                 }
157             } else {
158                 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
159             }
160         }
161     };
162
163     private setMaxLength = ():void => {
164         switch (this.$scope.editPropertyModel.property.type) {
165             case PROPERTY_TYPES.MAP:
166             case PROPERTY_TYPES.LIST:
167                 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
168                     PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
169                     PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
170                 break;
171             case PROPERTY_TYPES.JSON:
172                 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
173                 break;
174             default:
175                 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
176         }
177     };
178
179
180     private initScope = ():void => {
181
182         //scope properties
183         this.$scope.forms = {};
184         this.$scope.validationPattern = this.ValidationPattern;
185         this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
186         this.$scope.commentValidationPattern = this.CommentValidationPattern;
187         this.$scope.isLoading = false;
188         this.$scope.isNew = (this.formState === FormState.CREATE);
189         this.$scope.isService = this.component.isService();
190         this.$scope.modalInstanceProperty = this.$uibModalInstance;
191         this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
192         this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
193         this.$scope.dataTypes = this.DataTypesService.getAllDataTypes();
194         this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
195         this.initEditPropertyModel();
196
197         //check if property of VnfConfiguration
198         this.$scope.isVnfConfiguration = false;
199         if(angular.isArray(this.component.componentInstances)) {
200             var componentPropertyOwner:ComponentInstance = this.component.componentInstances.find((ci:ComponentInstance) => {
201                 return ci.uniqueId === this.property.resourceInstanceUniqueId;
202             });
203             if (componentPropertyOwner.componentName === 'vnfConfiguration') {
204                 this.$scope.isVnfConfiguration = true;
205             }
206         }
207
208         this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
209             return this.$scope.editPropertyModel.types.indexOf(type) == -1;
210         });
211         this.initForNotSimpleType();
212
213
214         this.$scope.validateJson = (json:string):boolean => {
215             if (!json) {
216                 return true;
217             }
218             return this.ValidationUtils.validateJson(json);
219         };
220
221
222         //scope methods
223         this.$scope.save = (doNotCloseModal?:boolean):void => {
224             let property:PropertyModel = this.$scope.editPropertyModel.property;
225             this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
226             //if read only - or no changes made - just closes the modal
227             //need to check for property.value changes manually to detect if map properties deleted
228             if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
229                 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
230                 this.$uibModalInstance.close();
231                 return;
232             }
233
234             this.$scope.isLoading = true;
235
236             let onPropertyFaild = (response):void => {
237                 console.info('onFaild', response);
238                 this.$scope.isLoading = false;
239             };
240
241             let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
242                 console.info('onPropertyResourceSuccess : ', propertyFromBE);
243                 this.$scope.isLoading = false;
244
245                 if (!doNotCloseModal) {
246                     this.$uibModalInstance.close(propertyFromBE);
247                 } else {
248                     this.$scope.forms.editForm.$setPristine();
249                     this.$scope.editPropertyModel.property = new PropertyModel();
250                 }
251             };
252
253             //in case we have uniqueId we call update method
254             if (this.$scope.isPropertyValueOwner) {
255                 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
256                     let myValueString:string = JSON.stringify(this.$scope.myValue);
257                     property.value = myValueString;
258                 }
259                 this.component.updateInstanceProperty(property).then(onPropertySuccess, onPropertyFaild);
260             } else {
261                 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
262                     let myValueString:string = JSON.stringify(this.$scope.myValue);
263                     property.defaultValue = myValueString;
264                 } else {
265                     this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
266                 }
267                 this.component.addOrUpdateProperty(property).then(onPropertySuccess, onPropertyFaild);
268             }
269         };
270
271         this.$scope.getPrev = ():void=> {
272             this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
273             this.initResource();
274             this.initForNotSimpleType();
275             this.$scope.isLastProperty = false;
276         };
277
278         this.$scope.getNext = ():void=> {
279             this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
280             this.initResource();
281             this.initForNotSimpleType();
282             this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
283         };
284
285         this.$scope.isSimpleType = (typeName:string):boolean=> {
286             return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
287         };
288
289         this.$scope.showSchema = ():boolean => {
290             return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
291         };
292
293         this.$scope.getValidationPattern = (type:string):RegExp => {
294             return this.ValidationUtils.getValidationPattern(type);
295         };
296
297         this.$scope.validateIntRange = (value:string):boolean => {
298             return !value || this.ValidationUtils.validateIntRange(value);
299         };
300
301         this.$scope.close = ():void => {
302             this.$uibModalInstance.close();
303         };
304
305         // put default value when instance value is empty
306         this.$scope.onValueChange = ():void => {
307             if (!this.$scope.editPropertyModel.property.value) {
308                 if (this.$scope.isPropertyValueOwner) {
309                     this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
310                 }
311             }
312         };
313
314         // Add the done button at the footer.
315         this.$scope.footerButtons = [
316             {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
317             {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
318         ];
319
320         this.$scope.$watch("forms.editForm.$invalid", (newVal, oldVal) => {
321             this.$scope.footerButtons[0].disabled = this.$scope.forms.editForm.$invalid;
322         });
323
324         this.$scope.getDefaultValue = ():any => {
325             return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
326         };
327
328         this.$scope.onTypeChange = ():void => {
329             this.$scope.editPropertyModel.property.value = '';
330             this.$scope.editPropertyModel.property.defaultValue = '';
331             this.setMaxLength();
332             this.initForNotSimpleType();
333         };
334
335         this.$scope.onSchemaTypeChange = ():void => {
336             if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
337                 this.$scope.myValue = {'': null};
338             } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
339                 this.$scope.myValue = [];
340             }
341             this.setMaxLength();
342         };
343
344         this.$scope.delete = (property:PropertyModel):void => {
345             let onOk = ():void => {
346                 this.component.deleteProperty(property.uniqueId).then(
347                     this.$scope.close
348                 );
349             };
350             let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
351             let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
352             this.ModalsHandler.openConfirmationModal(title, message, false).then(onOk);
353         };
354     }
355 }