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, InputBEModel, Component, InputFEModel} 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 {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
29 import {SdcUiCommon, SdcUiComponents, SdcUiServices} from "onap-ui-angular";
30 import {CompositionService} from "app/ng2/pages/composition/composition.service";
31 import {WorkspaceService} from "app/ng2/pages/workspace/workspace.service";
32 import {Observable} from "rxjs";
33 import {TopologyTemplateService} from "app/ng2/services/component-services/topology-template.service";
34 import {InstanceFeDetails} from "../../../../models/instance-fe-details";
35 import {ToscaGetFunction} from "../../../../models/tosca-get-function";
36 import {ToscaFunctionValidationEvent} from "../../../../ng2/pages/properties-assignment/tosca-function/tosca-function.component";
38 export interface IEditPropertyModel {
39 property:PropertyModel;
41 simpleTypes:Array<string>;
42 hasGetFunctionValue: boolean;
43 isGetFunctionValid: boolean;
46 interface IPropertyFormViewModelScope extends ng.IScope {
48 editForm:ng.IFormController;
49 footerButtons:Array<any>;
53 componentMetadata: { isService: boolean, isVfc: boolean }
54 validationPattern:RegExp;
55 propertyNameValidationPattern:RegExp;
56 commentValidationPattern:RegExp;
57 editPropertyModel: IEditPropertyModel;
58 componentInstanceMap: Map<string, InstanceFeDetails>;
59 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
60 currentPropertyIndex:number;
61 isLastProperty:boolean;
63 nonPrimitiveTypes:Array<string>;
64 dataTypes:DataTypesMap;
65 isTypeDataType:boolean;
68 isPropertyValueOwner:boolean;
69 isVnfConfiguration:boolean;
71 modelNameFilter:string;
72 isGetFunctionValueType: boolean;
73 invalidMandatoryFields: boolean;
75 validateJson(json:string):boolean;
76 save(doNotCloseModal?:boolean):void;
77 getValidationPattern(type:string):RegExp;
78 validateIntRange(value:string):boolean;
81 onSchemaTypeChange():void;
82 onTypeChange(resetSchema:boolean):void;
84 delete(property:PropertyModel):void;
87 isSimpleType(typeName:string):boolean;
88 getDefaultValue():any;
89 onValueTypeChange(): void;
92 export class PropertyFormViewModel {
96 'Sdc.Services.DataTypesService',
100 'PropertyNameValidationPattern',
101 'CommentValidationPattern',
106 'filteredProperties',
109 'isPropertyValueOwner',
112 'ComponentInstanceServiceNg2',
113 'ComponentServiceNg2',
114 'TopologyTemplateService',
115 'CompositionService',
120 private formState:FormState;
122 constructor(private $scope:IPropertyFormViewModelScope,
123 private DataTypesService:DataTypesService,
124 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
125 private property:PropertyModel,
126 private ValidationPattern:RegExp,
127 private PropertyNameValidationPattern:RegExp,
128 private CommentValidationPattern:RegExp,
129 private ValidationUtils:ValidationUtils,
130 private component:Component,
131 private $filter:ng.IFilterService,
132 private modalService:SdcUiServices.ModalService,
133 private filteredProperties:Array<PropertyModel>,
134 private $timeout:ng.ITimeoutService,
135 private isViewOnly:boolean,
136 private isPropertyValueOwner:boolean,
137 private propertyOwnerType:string,
138 private propertyOwnerId:string,
139 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
140 private ComponentServiceNg2: ComponentServiceNg2,
141 private topologyTemplateService: TopologyTemplateService,
142 private compositionService: CompositionService,
143 private workspaceService: WorkspaceService,
144 private inputProperty : InputFEModel) {
146 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
150 private initResource = ():void => {
151 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
152 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
153 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
154 this.initToscaGetFunction();
158 private initToscaGetFunction() {
159 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaFunction();
160 this.$scope.editPropertyModel.isGetFunctionValid = true;
163 private isDataTypeForPropertyType = (property:PropertyModel):boolean=> {
164 property.simpleType = "";
165 if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
168 let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
170 property.simpleType = simpleType;
176 private getTypeForDataTypeDerivedFromSimple = (dataTypeName:string):string => {
177 if (!this.$scope.dataTypes[dataTypeName]) {
180 if (this.$scope.dataTypes[dataTypeName].derivedFromName == "tosca.datatypes.Root" || this.$scope.dataTypes[dataTypeName].properties) {
183 if (PROPERTY_DATA.SIMPLE_TYPES.indexOf(this.$scope.dataTypes[dataTypeName].derivedFromName) > -1) {
184 return this.$scope.dataTypes[dataTypeName].derivedFromName
186 return this.getTypeForDataTypeDerivedFromSimple(this.$scope.dataTypes[dataTypeName].derivedFromName);
189 private initForNotSimpleType = ():void => {
190 const property = this.$scope.editPropertyModel.property;
191 this.$scope.isTypeDataType = this.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
192 if (property.isToscaFunction()) {
193 this.initValueForGetFunction();
197 if (this.isComplexType(property.type)) {
198 if (property.value || property.defaultValue) {
199 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
201 this.initEmptyComplexValue(property.type);
206 private initValueForGetFunction(): void {
207 const property = this.$scope.editPropertyModel.property;
208 if (property.defaultValue) {
209 this.$scope.myValue = JSON.parse(property.defaultValue);
212 if (this.isComplexType(property.type)) {
213 this.initEmptyComplexValue(property.type);
217 this.$scope.myValue = undefined;
220 private initComponentInstanceMap() {
221 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
222 if (this.compositionService.componentInstances) {
223 this.compositionService.componentInstances.forEach(value => {
224 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
231 private initEmptyComplexValue(type: string): any {
233 case PROPERTY_TYPES.MAP:
234 this.$scope.myValue = {'': null};
236 case PROPERTY_TYPES.LIST:
237 this.$scope.myValue = [];
240 this.$scope.myValue = {};
244 private isComplexType(type: string): boolean {
248 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
251 private setMaxLength = ():void => {
252 switch (this.$scope.editPropertyModel.property.type) {
253 case PROPERTY_TYPES.MAP:
254 case PROPERTY_TYPES.LIST:
255 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
256 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
257 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
259 case PROPERTY_TYPES.JSON:
260 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
263 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
268 private initScope = ():void => {
271 this.$scope.isViewOnly = this.isViewOnly;
272 this.$scope.isLoading = true;
273 this.$scope.forms = {};
274 this.$scope.validationPattern = this.ValidationPattern;
275 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
276 this.$scope.commentValidationPattern = this.CommentValidationPattern;
277 this.$scope.nameMaxLength = PROPERTY_VALUE_CONSTRAINTS.NAME_MAX_LENGTH;
278 this.$scope.isNew = (this.formState === FormState.CREATE);
279 this.$scope.componentMetadata = {
280 isService: this.workspaceService.metadata.isService(),
281 isVfc: this.workspaceService.metadata.isVfc()
283 this.$scope.modalInstanceProperty = this.$uibModalInstance;
284 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
285 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
286 const property = new PropertyModel(this.property);
287 this.$scope.editPropertyModel = {
288 'property': property,
289 types: PROPERTY_DATA.TYPES,
290 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
291 hasGetFunctionValue: property.isToscaFunction(),
292 isGetFunctionValid: true,
294 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
295 this.$scope.propertyOwnerType = this.propertyOwnerType;
296 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
297 //check if property of VnfConfiguration
298 this.$scope.isVnfConfiguration = false;
299 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
300 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
301 return ci.uniqueId === this.property.resourceInstanceUniqueId;
303 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
304 this.$scope.isVnfConfiguration = true;
308 this.initComponentInstanceMap();
310 this.$scope.validateJson = (json:string):boolean => {
314 return this.ValidationUtils.validateJson(json);
317 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
318 this.$scope.dataTypes = response.data as DataTypesMap;
320 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
321 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
323 this.initForNotSimpleType();
324 this.$scope.isLoading = false;
328 this.$scope.save = (doNotCloseModal?:boolean):void => {
329 let property:PropertyModel = this.$scope.editPropertyModel.property;
330 this.$scope.isLoading = true;
331 if (property.propertyView){
332 if (property.constraints.length == 0) {
335 let input : InputBEModel = this.inputProperty;
336 input.constraints = property.constraints;
337 this.ComponentServiceNg2.updateComponentInputs(this.component, [input]).subscribe(
339 console.debug("Input property updated");
340 this.$uibModalInstance.close();
343 console.debug("Failed to update input property");
344 this.$uibModalInstance.close();
349 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
350 //if read only - or no changes made - just closes the modal
351 //need to check for property.value changes manually to detect if map properties deleted
352 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
353 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
354 this.$uibModalInstance.close();
358 this.$scope.isLoading = true;
360 let onPropertyFailure = (response):void => {
361 console.error('Failed to update property', response);
362 this.$scope.isLoading = false;
365 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
366 this.$scope.isLoading = false;
367 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
368 if (!doNotCloseModal) {
369 this.$uibModalInstance.close(propertyFromBE);
371 this.$scope.forms.editForm.$setPristine();
372 this.$scope.editPropertyModel.property = new PropertyModel();
376 //Not clean, but doing this as a temporary fix until we update the property right panel modals
377 if (this.propertyOwnerType === "group"){
378 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
379 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
380 } else if (this.propertyOwnerType === "policy"){
381 if (!this.$scope.editPropertyModel.property.simpleType &&
382 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
383 !_.isNil(this.$scope.myValue)) {
384 property.value = JSON.stringify(this.$scope.myValue);
386 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
387 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
389 //in case we have uniqueId we call update method
390 if (this.$scope.isPropertyValueOwner) {
391 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
392 property.value = JSON.stringify(this.$scope.myValue);
394 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
395 error => onPropertyFailure(error));
397 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
398 property.defaultValue = JSON.stringify(this.$scope.myValue);
400 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
402 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
407 this.$scope.getPrev = ():void=> {
408 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
410 this.initForNotSimpleType();
411 this.$scope.isLastProperty = false;
414 this.$scope.getNext = ():void=> {
415 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
417 this.initForNotSimpleType();
418 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
421 this.$scope.isSimpleType = (typeName:string):boolean=> {
422 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
425 this.$scope.showSchema = ():boolean => {
426 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
429 this.$scope.getValidationPattern = (type:string):RegExp => {
430 return this.ValidationUtils.getValidationPattern(type);
433 this.$scope.validateIntRange = (value:string):boolean => {
434 return !value || this.ValidationUtils.validateIntRange(value);
437 this.$scope.close = ():void => {
438 this.$uibModalInstance.close();
441 // put default value when instance value is empty
442 this.$scope.onValueChange = ():void => {
443 if (!this.$scope.editPropertyModel.property.value) {
444 if (this.$scope.isPropertyValueOwner) {
445 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
450 // Add the done button at the footer.
451 this.$scope.footerButtons = [
452 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
453 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
456 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
457 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
458 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
459 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
461 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
462 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
466 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
467 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
468 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
469 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
471 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
472 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
476 this.$scope.getDefaultValue = ():any => {
477 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
480 this.$scope.onTypeChange = ():void => {
481 this.$scope.editPropertyModel.property.value = '';
482 this.$scope.editPropertyModel.property.defaultValue = '';
484 this.initForNotSimpleType();
487 this.$scope.onSchemaTypeChange = ():void => {
488 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
489 this.$scope.myValue = {};
490 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
491 this.$scope.myValue = [];
496 this.$scope.delete = (property:PropertyModel):void => {
497 let onOk: Function = ():void => {
498 this.deleteProperty(property.uniqueId).subscribe(
502 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
503 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
504 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
505 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
508 this.$scope.onValueTypeChange = (): void => {
509 this.setEmptyValue();
510 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
511 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
513 this.$scope.editPropertyModel.property.toscaFunction = undefined;
514 this.$scope.editPropertyModel.isGetFunctionValid = true;
518 this.$scope.onConstraintChange = (constraints: any): void => {
519 if (!this.$scope.invalidMandatoryFields) {
520 this.$scope.footerButtons[0].disabled = !constraints.valid;
522 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
524 if (!constraints.constraints || constraints.constraints.length == 0) {
525 this.$scope.editPropertyModel.property.propertyConstraints = null;
526 this.$scope.editPropertyModel.property.constraints = null;
529 this.$scope.editPropertyModel.property.propertyConstraints = this.serializePropertyConstraints(constraints.constraints);
530 this.$scope.editPropertyModel.property.constraints = constraints.constraints;
533 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
534 this.$scope.editPropertyModel.property.toscaFunction = toscaGetFunction;
537 this.$scope.onToscaFunctionValidityChange = (validationEvent: ToscaFunctionValidationEvent): void => {
538 if (validationEvent.isValid) {
539 this.$scope.editPropertyModel.isGetFunctionValid = true;
542 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
546 private serializePropertyConstraints(constraints: any[]): string[] {
548 let stringConstrsints = new Array();
549 constraints.forEach((constraint) => {
550 stringConstrsints.push(JSON.stringify(constraint));
552 return stringConstrsints;
557 private setEmptyValue() {
558 const property1 = this.$scope.editPropertyModel.property;
559 property1.value = undefined;
560 if (this.isComplexType(property1.type)) {
561 this.initEmptyComplexValue(property1.type);
564 this.$scope.myValue = '';
567 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
569 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
570 .map(newProperties => {
571 newProperties.forEach((newProperty) => {
572 if (!_.isNil(newProperty.path)) {
573 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
574 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
575 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
576 uniqueId: newProperty.uniqueId,
577 path: newProperty.path
579 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
580 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
583 return newProperties;
587 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
588 if (!property.uniqueId) {
589 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
590 this.filteredProperties.push(newProperty);
593 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
596 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
597 // find exist instance property in parent component for update the new value ( find bu uniqueId )
598 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
599 let propertyIndex = this.filteredProperties.indexOf(existProperty);
600 this.filteredProperties[propertyIndex] = newProperty;
603 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
607 public deleteProperty = (propertyId:string):Observable<void> => {
608 let onSuccess = ():void => {
609 console.debug("Property deleted");
610 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
612 let onFailed = ():void => {
613 console.debug("Failed to delete property");
615 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);