2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
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';
29 export class PropertyFEModel extends PropertyBEModel {
31 expandedChildPropertyId: string;
32 flattenedChildren: Array<DerivedFEProperty>;
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;
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;
47 constructor(property: PropertyBEModel){
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;
56 this.updateValueObjOrig();
57 this.resetValueObjValidation();
58 this.origName = this.name;
62 public updateValueObj(valueObj:any, isValid:boolean) {
63 this.valueObj = PropertyFEModel.cleanValueObj(valueObj);
64 this.valueObjValidation = this.valueObjIsValid = isValid;
65 this.valueObjIsChanged = this.hasValueObjChanged();
68 public updateValueObjOrig() {
69 this.valueObjOrig = _.cloneDeep(this.valueObj);
70 this.valueObjIsChanged = false;
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]));
80 return Boolean(valueObjValidation);
83 public resetValueObjValidation() {
84 if (this.derivedDataType === DerivedPropertyType.SIMPLE) {
85 this.valueObjValidation = null;
86 } else if (this.derivedDataType === DerivedPropertyType.LIST) {
87 this.valueObjValidation = [];
89 this.valueObjValidation = {};
91 this.valueObjIsValid = true;
94 public getJSONValue = (): string => {
95 return PropertyFEModel.stringifyValueObj(this.valueObj, this.schema.property.type, this.derivedDataType);
98 public getValueObj = (): any => {
99 return PropertyFEModel.parseValueObj(this.value, this.type, this.derivedDataType, this.defaultValue);
102 public setNonDeclared = (childPath?: string): void => {
103 if (!childPath) { //un-declaring a child prop
104 this.isDeclared = false;
106 let childProp: DerivedFEProperty = this.flattenedChildren.find(child => child.propertiesName == childPath);
107 childProp.isDeclared = false;
111 public setAsDeclared = (childNameToDeclare?:string): void => {
112 if (!childNameToDeclare) { //declaring a child prop
113 this.isSelected = false;
114 this.isDeclared = true;
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;
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;
128 this.expandedChildPropertyId = this.name;
132 public getIndexOfChild = (childPropName: string): number => {
133 return this.flattenedChildren.findIndex(prop => prop.propertiesName.indexOf(childPropName) === 0);
136 public getCountOfChildren = (childPropName: string):number => {
137 let matchingChildren:Array<DerivedFEProperty> = this.flattenedChildren.filter(prop => prop.propertiesName.indexOf(childPropName) === 0) || [];
138 return matchingChildren.length;
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)
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);
157 _.set(this.valueObj, childPropName, null);
160 _.set(this.valueObj, childPropName, childProp.valueObj);
162 if (childProp.valueObjIsChanged) {
163 _.set(this.valueObjValidation, childPropName, childProp.valueObjIsValid);
164 this.valueObjIsValid = childProp.valueObjIsValid && this.calculateValueObjIsValid();
165 this.valueObjIsChanged = true;
167 _.unset(this.valueObjValidation, childPropName);
168 this.valueObjIsValid = this.calculateValueObjIsValid();
169 this.valueObjIsChanged = this.hasValueObjChanged();
174 childPropMapKeyUpdated = (childProp: DerivedFEProperty, newMapKey: string, forceValidate: boolean = false) => {
175 if (!childProp.isChildOfListOrMap || childProp.derivedDataType !== DerivedPropertyType.MAP) {
178 const childParentNames = this.getParentNamesArray(childProp.parentName);
179 const oldActualMapKey = childProp.getActualMapKey();
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.';
192 childProp.mapKeyError = null;
194 const newActualMapKey = childProp.getActualMapKey();
195 const newMapKeyIsValid = !childProp.mapKeyError;
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;
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));
211 // remove map key from valueObj and valueObjValidation
212 _.unset(this.valueObj, oldChildPropNames);
213 _.unset(this.valueObjValidation, oldChildPropNames);
215 // force validate after map key change
216 forceValidate = true;
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);
225 _.unset(this.valueObjValidation, childMapKeyNames);
228 this.valueObjIsValid = newMapKeyIsValid && this.calculateValueObjIsValid();
229 this.valueObjIsChanged = this.hasValueObjChanged();
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
238 let parentProp: DerivedFEProperty = this.flattenedChildren.find(prop => prop.propertiesName === parentPropName);
239 let nameToInsert: string = parentProp.name;
241 if (parentProp.isChildOfListOrMap) {
242 if (!noHashKeys && parentProp.derivedDataType == DerivedPropertyType.MAP && !parentProp.mapInlist) {
243 nameToInsert = parentProp.getActualMapKey();
245 let siblingProps = this.flattenedChildren.filter(prop => prop.parentName == parentProp.parentName).map(prop => prop.propertiesName);
246 nameToInsert = siblingProps.indexOf(parentProp.propertiesName).toString();
250 parentNames.splice(0, 0, nameToInsert); //add prop name to array
251 return this.getParentNamesArray(parentProp.parentName, parentNames, noHashKeys); //continue recursing
254 public hasValueObjChanged() {
255 return !_.isEqual(this.valueObj, this.valueObjOrig);
258 static stringifyValueObj(valueObj: any, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType): string {
259 // if valueObj is null, return null
260 if (valueObj === null || valueObj === undefined) {
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) {
268 return JSON.stringify(valueObj.map(item => (typeof item == 'string') ? JSON.parse(item) : item));
272 // if type is anything but string, then stringify valueObj
273 if ((typeof valueObj) !== 'string') {
274 return JSON.stringify(valueObj);
277 // return trimmed string value
278 return valueObj.trim();
281 static parseValueObj(value: string, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType, defaultValue?: string): any {
283 if (propertyDerivedType === DerivedPropertyType.SIMPLE) {
284 valueObj = value || defaultValue || null; // use null for empty value object
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
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.
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.
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 === '') {
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) {
315 // if unsetEmpty flag is true and valueObj is empty
316 if (unsetEmpty && !Object.keys(valueObj).length) {