d4b45408ca06ce088d23e095893191c0cb9f9ad6
[sdc.git] / catalog-ui / src / app / models / properties-inputs / property-fe-model.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (C) 2020 Nokia
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 import * as _ from "lodash";
24 import {SchemaPropertyGroupModel, SchemaProperty} from '../schema-property';
25 import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils';
26 import { FilterPropertiesAssignmentData, PropertyBEModel, DerivedPropertyType, DerivedFEPropertyMap, DerivedFEProperty } from 'app/models';
27
28
29 export class PropertyFEModel extends PropertyBEModel {
30
31     expandedChildPropertyId: string;
32     flattenedChildren:  Array<DerivedFEProperty>;
33     isDeclared: boolean;
34     isDisabled: boolean;
35     isSelected: boolean;
36     isSimpleType: boolean; //for convenience only - we can really just check if derivedDataType == derivedPropertyTypes.SIMPLE to know if the prop is simple
37     propertiesName: string;
38     uniqueId: string;
39     valueObj: any; //this is the only value we relate to in the html templates
40     valueObjValidation: any;
41     valueObjIsValid: boolean;
42     valueObjOrig: any; //this is valueObj representation as saved in server
43     valueObjIsChanged: boolean;
44     derivedDataType: DerivedPropertyType;
45     origName: string;
46
47     constructor(property: PropertyBEModel){
48         super(property);
49         this.value = property.value ? property.value : property.defaultValue;//In FE if a property doesn't have value - display the default value
50         this.isSimpleType = PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.type) > -1;
51         this.setNonDeclared();
52         this.derivedDataType = this.getDerivedPropertyType();
53         this.flattenedChildren = [];
54         this.propertiesName = this.name;
55         this.valueObj = null;
56         this.updateValueObjOrig();
57         this.resetValueObjValidation();
58         this.origName = this.name;
59     }
60
61
62     public updateValueObj(valueObj:any, isValid:boolean) {
63         this.valueObj = PropertyFEModel.cleanValueObj(valueObj);
64         this.valueObjValidation = this.valueObjIsValid = isValid;
65         this.valueObjIsChanged = this.hasValueObjChanged();
66     }
67
68     public updateValueObjOrig() {
69         this.valueObjOrig = _.cloneDeep(this.valueObj);
70         this.valueObjIsChanged = false;
71     }
72
73     public calculateValueObjIsValid(valueObjValidation?: any) {
74         valueObjValidation = (valueObjValidation !== undefined) ? valueObjValidation : this.valueObjValidation;
75         if (valueObjValidation instanceof Array) {
76             return valueObjValidation.every((v) => this.calculateValueObjIsValid(v));
77         } else if (valueObjValidation instanceof Object) {
78             return Object.keys(valueObjValidation).every((k) => this.calculateValueObjIsValid(valueObjValidation[k]));
79         }
80         return Boolean(valueObjValidation);
81     }
82
83     public resetValueObjValidation() {
84         if (this.derivedDataType === DerivedPropertyType.SIMPLE) {
85             this.valueObjValidation = null;
86         } else if (this.derivedDataType === DerivedPropertyType.LIST) {
87             this.valueObjValidation = [];
88         } else {
89             this.valueObjValidation = {};
90         }
91         this.valueObjIsValid = true;
92     }
93
94     public getJSONValue = (): string => {
95         return PropertyFEModel.stringifyValueObj(this.valueObj, this.schema.property.type, this.derivedDataType);
96     }
97
98     public getValueObj = (): any => {
99         return PropertyFEModel.parseValueObj(this.value, this.type, this.derivedDataType, this.defaultValue);
100     }
101
102     public setNonDeclared = (childPath?: string): void => {
103         if (!childPath) { //un-declaring a child prop
104             this.isDeclared = false;
105         } else {
106             let childProp: DerivedFEProperty = this.flattenedChildren.find(child => child.propertiesName == childPath);
107             childProp.isDeclared = false;
108         }
109     }
110
111     public setAsDeclared = (childNameToDeclare?:string): void => {
112         if (!childNameToDeclare) { //declaring a child prop
113             this.isSelected = false;
114             this.isDeclared = true;
115         } else {
116             let childProp: DerivedFEProperty = this.flattenedChildren.find(child => child.propertiesName == childNameToDeclare);
117             if (!childProp) { console.log("ERROR: Unabled to find child: " + childNameToDeclare, this); return; }
118             childProp.isSelected = false;
119             childProp.isDeclared = true;
120         }
121     }
122
123     //For expand-collapse functionality - used within HTML template
124     public updateExpandedChildPropertyId = (childPropertyId: string): void => {
125         if (childPropertyId.lastIndexOf('#') > -1) {
126             this.expandedChildPropertyId = (this.expandedChildPropertyId == childPropertyId) ? (childPropertyId.substring(0, childPropertyId.lastIndexOf('#'))) : childPropertyId;
127         } else {
128             this.expandedChildPropertyId = this.name;
129         }
130     }
131
132     public getIndexOfChild = (childPropName: string): number => {
133         return this.flattenedChildren.findIndex(prop => prop.propertiesName.indexOf(childPropName) === 0);
134     }
135
136     public getCountOfChildren = (childPropName: string):number => {
137         let matchingChildren:Array<DerivedFEProperty> = this.flattenedChildren.filter(prop => prop.propertiesName.indexOf(childPropName) === 0) || [];
138         return matchingChildren.length;
139     }
140
141     // public getListIndexOfChild = (childPropName: string): number => { //gets list of siblings and then the index within that list
142     //     this.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName)
143     // }
144
145     /* Updates parent valueObj when a child prop's value has changed */
146     public childPropUpdated = (childProp: DerivedFEProperty): void => {
147         let parentNames = this.getParentNamesArray(childProp.propertiesName, []);
148         if (parentNames.length) {
149             const childPropName = parentNames.join('.');
150             // unset value only if is null and valid, and not in a list
151             if (childProp.valueObj === null && childProp.valueObjIsValid) {
152                 const parentChildProp = this.flattenedChildren.find((ch) => ch.propertiesName === childProp.parentName) || this;
153                 if (parentChildProp.derivedDataType !== DerivedPropertyType.LIST) {
154                     _.unset(this.valueObj, childPropName);
155                     this.valueObj = PropertyFEModel.cleanValueObj(this.valueObj);
156                 } else {
157                     _.set(this.valueObj, childPropName, null);
158                 }
159             } else {
160                 _.set(this.valueObj, childPropName, childProp.valueObj);        
161             }
162             if (childProp.valueObjIsChanged) {
163                 _.set(this.valueObjValidation, childPropName, childProp.valueObjIsValid);
164                 this.valueObjIsValid = childProp.valueObjIsValid && this.calculateValueObjIsValid();
165                 this.valueObjIsChanged = true;
166             } else {
167                 _.unset(this.valueObjValidation, childPropName);
168                 this.valueObjIsValid = this.calculateValueObjIsValid();
169                 this.valueObjIsChanged = this.hasValueObjChanged();
170             }
171         }
172     };
173
174     childPropMapKeyUpdated = (childProp: DerivedFEProperty, newMapKey: string, forceValidate: boolean = false) => {
175         if (!childProp.isChildOfListOrMap || childProp.derivedDataType !== DerivedPropertyType.MAP) {
176             return;
177         }
178         const childParentNames = this.getParentNamesArray(childProp.parentName);
179         const oldActualMapKey = childProp.getActualMapKey();
180
181         childProp.mapKey = newMapKey;
182         if (childProp.mapKey === null) {  // null -> remove map key
183             childProp.mapKeyError = null;
184         } else if (!childProp.mapKey) {
185             childProp.mapKeyError = 'Key cannot be empty.';
186         } else if (this.flattenedChildren
187                 .filter((fch) => fch !== childProp && fch.parentName === childProp.parentName)  // filter sibling child props
188                 .map((fch) => fch.mapKey)
189                 .indexOf(childProp.mapKey) !== -1) {
190             childProp.mapKeyError = 'This key already exists.';
191         } else {
192             childProp.mapKeyError = null;
193         }
194         const newActualMapKey = childProp.getActualMapKey();
195         const newMapKeyIsValid = !childProp.mapKeyError;
196
197         // if mapKey was changed, then replace the old key with the new one
198         if (newActualMapKey !== oldActualMapKey) {
199             const oldChildPropNames = childParentNames.concat([oldActualMapKey]);
200             const newChildPropNames = (newActualMapKey) ? childParentNames.concat([newActualMapKey]) : null;
201
202             // add map key to valueObj and valueObjValidation
203             if (newChildPropNames) {
204                 const newChildVal = _.get(this.valueObj, oldChildPropNames);
205                 if (newChildVal !== undefined) {
206                     _.set(this.valueObj, newChildPropNames, newChildVal);
207                     _.set(this.valueObjValidation, newChildPropNames, _.get(this.valueObjValidation, oldChildPropNames, childProp.valueObjIsValid));
208                 }
209             }
210
211             // remove map key from valueObj and valueObjValidation
212             _.unset(this.valueObj, oldChildPropNames);
213             _.unset(this.valueObjValidation, oldChildPropNames);
214
215             // force validate after map key change
216             forceValidate = true;
217         }
218
219         if (forceValidate) {
220             // add custom entry for map key validation:
221             const childMapKeyNames = childParentNames.concat(`%%KEY:${childProp.name}%%`);
222             if (newActualMapKey) {
223                 _.set(this.valueObjValidation, childMapKeyNames, newMapKeyIsValid);
224             } else {
225                 _.unset(this.valueObjValidation, childMapKeyNames);
226             }
227
228             this.valueObjIsValid = newMapKeyIsValid && this.calculateValueObjIsValid();
229             this.valueObjIsChanged = this.hasValueObjChanged();
230         }
231     };
232
233     /* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
234     public getParentNamesArray = (parentPropName: string, parentNames?: Array<string>, noHashKeys:boolean = false): Array<string> => {
235         parentNames = parentNames || [];
236         if (parentPropName.indexOf("#") == -1) { return parentNames; } //finished recursing parents. return
237
238         let parentProp: DerivedFEProperty = this.flattenedChildren.find(prop => prop.propertiesName === parentPropName);
239         let nameToInsert: string = parentProp.name;
240
241         if (parentProp.isChildOfListOrMap) {
242             if (!noHashKeys && parentProp.derivedDataType == DerivedPropertyType.MAP && !parentProp.mapInlist) {
243                 nameToInsert = parentProp.getActualMapKey();
244             } else { //LIST
245                 let siblingProps = this.flattenedChildren.filter(prop => prop.parentName == parentProp.parentName).map(prop => prop.propertiesName);
246                 nameToInsert = siblingProps.indexOf(parentProp.propertiesName).toString();
247             }
248         }
249
250         parentNames.splice(0, 0, nameToInsert); //add prop name to array
251         return this.getParentNamesArray(parentProp.parentName, parentNames, noHashKeys); //continue recursing
252     }
253
254     public hasValueObjChanged() {
255         return !_.isEqual(this.valueObj, this.valueObjOrig);
256     }
257
258     static stringifyValueObj(valueObj: any, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType): string {
259         // if valueObj is null, return null
260         if (valueObj === null || valueObj === undefined) {
261             return null;
262         }
263
264         //If type is JSON, need to try parsing it before we stringify it so that it appears property in TOSCA - change per Bracha due to AMDOCS
265         //TODO: handle this.derivedDataType == DerivedPropertyType.MAP
266         if (propertyDerivedType == DerivedPropertyType.LIST && propertyType == PROPERTY_TYPES.JSON) {
267             try {
268                 return JSON.stringify(valueObj.map(item => (typeof item == 'string') ? JSON.parse(item) : item));
269             } catch (e){}
270         }
271
272         // if type is anything but string, then stringify valueObj
273         if ((typeof valueObj) !== 'string') {
274             return JSON.stringify(valueObj);
275         }
276
277         // return trimmed string value
278         return valueObj.trim();
279     }
280
281     static parseValueObj(value: string, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType, defaultValue?: string): any {
282         let valueObj;
283         if (propertyDerivedType === DerivedPropertyType.SIMPLE) {
284             valueObj = value || defaultValue || null;  // use null for empty value object
285             if (valueObj &&
286                 propertyType !== PROPERTY_TYPES.STRING &&
287                 propertyType !== PROPERTY_TYPES.JSON &&
288                 PROPERTY_DATA.SCALAR_TYPES.indexOf(<string>propertyType) == -1) {
289                 valueObj = JSON.parse(value);  // the value object contains the real value ans not the value as string
290             }
291         } else if (propertyDerivedType == DerivedPropertyType.LIST) {
292             valueObj = _.merge([], JSON.parse(defaultValue || '[]'), JSON.parse(value || '[]'));  // value object should be merged value and default value. Value takes higher precedence. Set value object to empty obj if undefined.
293         } else {
294             valueObj = _.merge({}, JSON.parse(defaultValue || '{}'), JSON.parse(value || '{}'));  // value object should be merged value and default value. Value takes higher precedence. Set value object to empty obj if undefined.
295         }
296         return valueObj;
297     };
298
299     static cleanValueObj(valueObj: any, unsetEmpty?: boolean): any {
300         // By default - unsetEmpty undefined - will make valueObj cleaned (no null or empty objects, but array will keep null or empty objects).
301         if (valueObj === undefined || valueObj === null || valueObj === '') {
302             return null;
303         }
304         if (valueObj instanceof Array) {
305             const cleanArr = valueObj.map((v) => PropertyFEModel.cleanValueObj(v)).filter((v) => v !== null);
306             valueObj.splice(0, valueObj.length, ...cleanArr)
307         } else if (valueObj instanceof Object) {
308             Object.keys(valueObj).forEach((k) => {
309                 // clean each item in the valueObj (by default, unset empty objects)
310                 valueObj[k] = PropertyFEModel.cleanValueObj(valueObj[k], unsetEmpty !== undefined ? unsetEmpty : true);
311                 if (valueObj[k] === null) {
312                     delete valueObj[k];
313                 }
314             });
315             // if unsetEmpty flag is true and valueObj is empty
316             if (unsetEmpty && !Object.keys(valueObj).length) {
317                 return null;
318             }
319         }
320         return valueObj;
321     }
322 }