2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
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";
36 export interface IEditPropertyModel {
37 property:PropertyModel;
39 simpleTypes:Array<string>;
40 hasGetFunctionValue: boolean;
41 isGetFunctionValid: boolean;
44 interface IPropertyFormViewModelScope extends ng.IScope {
46 editForm:ng.IFormController;
47 footerButtons:Array<any>;
50 componentMetadata: { isService: boolean, isVfc: boolean }
51 validationPattern:RegExp;
52 propertyNameValidationPattern:RegExp;
53 commentValidationPattern:RegExp;
54 editPropertyModel: IEditPropertyModel;
55 componentInstanceMap: Map<string, InstanceFeDetails>;
56 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
57 currentPropertyIndex:number;
58 isLastProperty:boolean;
60 nonPrimitiveTypes:Array<string>;
61 dataTypes:DataTypesMap;
62 isTypeDataType:boolean;
64 isPropertyValueOwner:boolean;
65 isVnfConfiguration:boolean;
67 modelNameFilter:string;
68 isGetFunctionValueType: boolean;
70 validateJson(json:string):boolean;
71 save(doNotCloseModal?:boolean):void;
72 getValidationPattern(type:string):RegExp;
73 validateIntRange(value:string):boolean;
76 onSchemaTypeChange():void;
77 onTypeChange(resetSchema:boolean):void;
79 delete(property:PropertyModel):void;
82 isSimpleType(typeName:string):boolean;
83 getDefaultValue():any;
84 onValueTypeChange(): void;
87 export class PropertyFormViewModel {
91 'Sdc.Services.DataTypesService',
95 'PropertyNameValidationPattern',
96 'CommentValidationPattern',
101 'filteredProperties',
103 'isPropertyValueOwner',
106 'ComponentInstanceServiceNg2',
107 'TopologyTemplateService',
108 'CompositionService',
112 private formState:FormState;
114 constructor(private $scope:IPropertyFormViewModelScope,
115 private DataTypesService:DataTypesService,
116 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
117 private property:PropertyModel,
118 private ValidationPattern:RegExp,
119 private PropertyNameValidationPattern:RegExp,
120 private CommentValidationPattern:RegExp,
121 private ValidationUtils:ValidationUtils,
122 // private component:Component,
123 private $filter:ng.IFilterService,
124 private modalService:SdcUiServices.ModalService,
125 private filteredProperties:Array<PropertyModel>,
126 private $timeout:ng.ITimeoutService,
127 private isPropertyValueOwner:boolean,
128 private propertyOwnerType:string,
129 private propertyOwnerId:string,
130 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
131 private topologyTemplateService: TopologyTemplateService,
132 private compositionService: CompositionService,
133 private workspaceService: WorkspaceService) {
135 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
139 private initResource = ():void => {
140 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
141 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
142 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.value || this.$scope.editPropertyModel.property.defaultValue;
143 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
144 this.initToscaGetFunction();
148 private initToscaGetFunction() {
149 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaGetFunction();
150 this.$scope.editPropertyModel.isGetFunctionValid = true;
153 private initForNotSimpleType = ():void => {
154 const property = this.$scope.editPropertyModel.property;
155 this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
156 if (property.isToscaGetFunction()) {
157 this.initValueForGetFunction();
161 if (this.isComplexType(property.type)) {
162 if (property.value || property.defaultValue) {
163 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
165 this.initEmptyComplexValue(property.type);
170 private initValueForGetFunction(): void {
171 const property = this.$scope.editPropertyModel.property;
172 if (property.defaultValue) {
173 this.$scope.myValue = JSON.parse(property.defaultValue);
176 if (this.isComplexType(property.type)) {
177 this.initEmptyComplexValue(property.type);
181 this.$scope.myValue = undefined;
184 private initComponentInstanceMap() {
185 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
186 if (this.compositionService.componentInstances) {
187 this.compositionService.componentInstances.forEach(value => {
188 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
195 private initEmptyComplexValue(type: string): any {
197 case PROPERTY_TYPES.MAP:
198 this.$scope.myValue = {'': null};
200 case PROPERTY_TYPES.LIST:
201 this.$scope.myValue = [];
204 this.$scope.myValue = {};
208 private isComplexType(type: string): boolean {
212 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
215 private setMaxLength = ():void => {
216 switch (this.$scope.editPropertyModel.property.type) {
217 case PROPERTY_TYPES.MAP:
218 case PROPERTY_TYPES.LIST:
219 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
220 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
221 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
223 case PROPERTY_TYPES.JSON:
224 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
227 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
232 private initScope = ():void => {
235 this.$scope.isLoading = true;
236 this.$scope.forms = {};
237 this.$scope.validationPattern = this.ValidationPattern;
238 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
239 this.$scope.commentValidationPattern = this.CommentValidationPattern;
240 this.$scope.isNew = (this.formState === FormState.CREATE);
241 this.$scope.componentMetadata = {
242 isService: this.workspaceService.metadata.isService(),
243 isVfc: this.workspaceService.metadata.isVfc()
245 this.$scope.modalInstanceProperty = this.$uibModalInstance;
246 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
247 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
248 const property = new PropertyModel(this.property);
249 this.$scope.editPropertyModel = {
250 'property': property,
251 types: PROPERTY_DATA.TYPES,
252 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
253 hasGetFunctionValue: property.isToscaGetFunction(),
254 isGetFunctionValid: true,
256 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
257 this.$scope.propertyOwnerType = this.propertyOwnerType;
258 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
259 //check if property of VnfConfiguration
260 this.$scope.isVnfConfiguration = false;
261 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
262 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
263 return ci.uniqueId === this.property.resourceInstanceUniqueId;
265 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
266 this.$scope.isVnfConfiguration = true;
270 this.initForNotSimpleType();
271 this.initComponentInstanceMap();
273 this.$scope.validateJson = (json:string):boolean => {
277 return this.ValidationUtils.validateJson(json);
280 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
281 this.$scope.dataTypes = response.data as DataTypesMap;
282 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
283 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
286 this.$scope.isLoading = false;
290 this.$scope.save = (doNotCloseModal?:boolean):void => {
291 let property:PropertyModel = this.$scope.editPropertyModel.property;
292 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
293 //if read only - or no changes made - just closes the modal
294 //need to check for property.value changes manually to detect if map properties deleted
295 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
296 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
297 this.$uibModalInstance.close();
301 this.$scope.isLoading = true;
303 let onPropertyFailure = (response):void => {
304 console.error('Failed to update property', response);
305 this.$scope.isLoading = false;
308 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
309 this.$scope.isLoading = false;
310 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
311 if (!doNotCloseModal) {
312 this.$uibModalInstance.close(propertyFromBE);
314 this.$scope.forms.editForm.$setPristine();
315 this.$scope.editPropertyModel.property = new PropertyModel();
319 //Not clean, but doing this as a temporary fix until we update the property right panel modals
320 if (this.propertyOwnerType === "group"){
321 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
322 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
323 } else if (this.propertyOwnerType === "policy"){
324 if (!this.$scope.editPropertyModel.property.simpleType &&
325 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
326 !_.isNil(this.$scope.myValue)) {
327 property.value = JSON.stringify(this.$scope.myValue);
329 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
330 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
332 //in case we have uniqueId we call update method
333 if (this.$scope.isPropertyValueOwner) {
334 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
335 property.value = JSON.stringify(this.$scope.myValue);
337 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
338 error => onPropertyFailure(error));
340 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
341 property.defaultValue = JSON.stringify(this.$scope.myValue);
343 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
345 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
350 this.$scope.getPrev = ():void=> {
351 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
353 this.initForNotSimpleType();
354 this.$scope.isLastProperty = false;
357 this.$scope.getNext = ():void=> {
358 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
360 this.initForNotSimpleType();
361 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
364 this.$scope.isSimpleType = (typeName:string):boolean=> {
365 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
368 this.$scope.showSchema = ():boolean => {
369 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
372 this.$scope.getValidationPattern = (type:string):RegExp => {
373 return this.ValidationUtils.getValidationPattern(type);
376 this.$scope.validateIntRange = (value:string):boolean => {
377 return !value || this.ValidationUtils.validateIntRange(value);
380 this.$scope.close = ():void => {
381 this.$uibModalInstance.close();
384 // put default value when instance value is empty
385 this.$scope.onValueChange = ():void => {
386 if (!this.$scope.editPropertyModel.property.value) {
387 if (this.$scope.isPropertyValueOwner) {
388 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
393 // Add the done button at the footer.
394 this.$scope.footerButtons = [
395 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
396 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
399 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
400 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
401 this.$scope.footerButtons[0].disabled = newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
403 this.$scope.footerButtons[0].disabled = newVal;
407 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
408 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
409 this.$scope.footerButtons[0].disabled = !newVal || !this.$scope.editPropertyModel.property.toscaGetFunction;
411 this.$scope.footerButtons[0].disabled = !newVal;
415 this.$scope.getDefaultValue = ():any => {
416 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
419 this.$scope.onTypeChange = ():void => {
420 this.$scope.editPropertyModel.property.value = '';
421 this.$scope.editPropertyModel.property.defaultValue = '';
423 this.initForNotSimpleType();
426 this.$scope.onSchemaTypeChange = ():void => {
427 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
428 this.$scope.myValue = {'': null};
429 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
430 this.$scope.myValue = [];
435 this.$scope.delete = (property:PropertyModel):void => {
436 let onOk: Function = ():void => {
437 this.deleteProperty(property.uniqueId).subscribe(
441 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
442 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
443 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
444 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
447 this.$scope.onValueTypeChange = (): void => {
448 this.setEmptyValue();
449 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
450 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
452 this.$scope.editPropertyModel.property.toscaGetFunction = undefined;
453 this.$scope.editPropertyModel.isGetFunctionValid = true;
457 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
458 this.$scope.editPropertyModel.property.toscaGetFunction = toscaGetFunction;
461 this.$scope.onGetFunctionValidityChange = (isValid: boolean): void => {
463 this.$scope.editPropertyModel.isGetFunctionValid = true;
466 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
471 private setEmptyValue() {
472 const property1 = this.$scope.editPropertyModel.property;
473 property1.value = undefined;
474 if (this.isComplexType(property1.type)) {
475 this.initEmptyComplexValue(property1.type);
478 this.$scope.myValue = '';
481 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
483 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
484 .map(newProperties => {
485 newProperties.forEach((newProperty) => {
486 if (!_.isNil(newProperty.path)) {
487 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
488 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
489 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
490 uniqueId: newProperty.uniqueId,
491 path: newProperty.path
493 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
494 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
497 return newProperties;
501 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
502 if (!property.uniqueId) {
503 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
504 this.filteredProperties.push(newProperty);
507 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
510 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
511 // find exist instance property in parent component for update the new value ( find bu uniqueId )
512 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
513 let propertyIndex = this.filteredProperties.indexOf(existProperty);
514 this.filteredProperties[propertyIndex] = newProperty;
517 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
521 public deleteProperty = (propertyId:string):Observable<void> => {
522 let onSuccess = ():void => {
523 console.debug("Property deleted");
524 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
526 let onFailed = ():void => {
527 console.debug("Failed to delete property");
529 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);