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";
35 import {ToscaFunctionValidationEvent} from "../../../../ng2/pages/properties-assignment/tosca-function/tosca-function.component";
37 export interface IEditPropertyModel {
38 property:PropertyModel;
40 simpleTypes:Array<string>;
41 hasGetFunctionValue: boolean;
42 isGetFunctionValid: boolean;
45 interface IPropertyFormViewModelScope extends ng.IScope {
47 editForm:ng.IFormController;
48 footerButtons:Array<any>;
52 componentMetadata: { isService: boolean, isVfc: boolean }
53 validationPattern:RegExp;
54 propertyNameValidationPattern:RegExp;
55 commentValidationPattern:RegExp;
56 editPropertyModel: IEditPropertyModel;
57 componentInstanceMap: Map<string, InstanceFeDetails>;
58 modalInstanceProperty:ng.ui.bootstrap.IModalServiceInstance;
59 currentPropertyIndex:number;
60 isLastProperty:boolean;
62 nonPrimitiveTypes:Array<string>;
63 dataTypes:DataTypesMap;
64 isTypeDataType:boolean;
67 isPropertyValueOwner:boolean;
68 isVnfConfiguration:boolean;
70 modelNameFilter:string;
71 isGetFunctionValueType: boolean;
72 invalidMandatoryFields: boolean;
74 validateJson(json:string):boolean;
75 save(doNotCloseModal?:boolean):void;
76 getValidationPattern(type:string):RegExp;
77 validateIntRange(value:string):boolean;
80 onSchemaTypeChange():void;
81 onTypeChange(resetSchema:boolean):void;
83 delete(property:PropertyModel):void;
86 isSimpleType(typeName:string):boolean;
87 getDefaultValue():any;
88 onValueTypeChange(): void;
91 export class PropertyFormViewModel {
95 'Sdc.Services.DataTypesService',
99 'PropertyNameValidationPattern',
100 'CommentValidationPattern',
105 'filteredProperties',
108 'isPropertyValueOwner',
111 'ComponentInstanceServiceNg2',
112 'TopologyTemplateService',
113 'CompositionService',
117 private formState:FormState;
119 constructor(private $scope:IPropertyFormViewModelScope,
120 private DataTypesService:DataTypesService,
121 private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
122 private property:PropertyModel,
123 private ValidationPattern:RegExp,
124 private PropertyNameValidationPattern:RegExp,
125 private CommentValidationPattern:RegExp,
126 private ValidationUtils:ValidationUtils,
127 // private component:Component,
128 private $filter:ng.IFilterService,
129 private modalService:SdcUiServices.ModalService,
130 private filteredProperties:Array<PropertyModel>,
131 private $timeout:ng.ITimeoutService,
132 private isViewOnly:boolean,
133 private isPropertyValueOwner:boolean,
134 private propertyOwnerType:string,
135 private propertyOwnerId:string,
136 private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
137 private topologyTemplateService: TopologyTemplateService,
138 private compositionService: CompositionService,
139 private workspaceService: WorkspaceService) {
141 this.formState = angular.isDefined(property.name) ? FormState.UPDATE : FormState.CREATE;
145 private initResource = ():void => {
146 this.$scope.editPropertyModel.property = new PropertyModel(this.property);
147 this.$scope.editPropertyModel.property.type = this.property.type ? this.property.type : null;
148 this.$scope.constraints = this.property.constraints && this.property.constraints[0] ? this.property.constraints[0]["validValues"] : null;
149 this.initToscaGetFunction();
153 private initToscaGetFunction() {
154 this.$scope.editPropertyModel.hasGetFunctionValue = this.$scope.editPropertyModel.property.isToscaFunction();
155 this.$scope.editPropertyModel.isGetFunctionValid = true;
158 private initForNotSimpleType = ():void => {
159 const property = this.$scope.editPropertyModel.property;
160 this.$scope.isTypeDataType = this.DataTypesService.isDataTypeForPropertyType(this.$scope.editPropertyModel.property);
161 if (property.isToscaFunction()) {
162 this.initValueForGetFunction();
166 if (this.isComplexType(property.type)) {
167 if (property.value || property.defaultValue) {
168 this.$scope.myValue = JSON.parse(property.value || property.defaultValue);
170 this.initEmptyComplexValue(property.type);
175 private initValueForGetFunction(): void {
176 const property = this.$scope.editPropertyModel.property;
177 if (property.defaultValue) {
178 this.$scope.myValue = JSON.parse(property.defaultValue);
181 if (this.isComplexType(property.type)) {
182 this.initEmptyComplexValue(property.type);
186 this.$scope.myValue = undefined;
189 private initComponentInstanceMap() {
190 this.$scope.componentInstanceMap = new Map<string, InstanceFeDetails>();
191 if (this.compositionService.componentInstances) {
192 this.compositionService.componentInstances.forEach(value => {
193 this.$scope.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
200 private initEmptyComplexValue(type: string): any {
202 case PROPERTY_TYPES.MAP:
203 this.$scope.myValue = {'': null};
205 case PROPERTY_TYPES.LIST:
206 this.$scope.myValue = [];
209 this.$scope.myValue = {};
213 private isComplexType(type: string): boolean {
217 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(type) == -1;
220 private setMaxLength = ():void => {
221 switch (this.$scope.editPropertyModel.property.type) {
222 case PROPERTY_TYPES.MAP:
223 case PROPERTY_TYPES.LIST:
224 this.$scope.maxLength = this.$scope.editPropertyModel.property.schema.property.type == PROPERTY_TYPES.JSON ?
225 PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH :
226 PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
228 case PROPERTY_TYPES.JSON:
229 this.$scope.maxLength = PROPERTY_VALUE_CONSTRAINTS.JSON_MAX_LENGTH;
232 this.$scope.maxLength =PROPERTY_VALUE_CONSTRAINTS.MAX_LENGTH;
237 private initScope = ():void => {
240 this.$scope.isViewOnly = this.isViewOnly;
241 this.$scope.isLoading = true;
242 this.$scope.forms = {};
243 this.$scope.validationPattern = this.ValidationPattern;
244 this.$scope.propertyNameValidationPattern = this.PropertyNameValidationPattern;
245 this.$scope.commentValidationPattern = this.CommentValidationPattern;
246 this.$scope.nameMaxLength = PROPERTY_VALUE_CONSTRAINTS.NAME_MAX_LENGTH;
247 this.$scope.isNew = (this.formState === FormState.CREATE);
248 this.$scope.componentMetadata = {
249 isService: this.workspaceService.metadata.isService(),
250 isVfc: this.workspaceService.metadata.isVfc()
252 this.$scope.modalInstanceProperty = this.$uibModalInstance;
253 this.$scope.currentPropertyIndex = _.findIndex(this.filteredProperties, i=> i.name == this.property.name);
254 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
255 const property = new PropertyModel(this.property);
256 this.$scope.editPropertyModel = {
257 'property': property,
258 types: PROPERTY_DATA.TYPES,
259 simpleTypes: PROPERTY_DATA.SIMPLE_TYPES,
260 hasGetFunctionValue: property.isToscaFunction(),
261 isGetFunctionValid: true,
263 this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
264 this.$scope.propertyOwnerType = this.propertyOwnerType;
265 this.$scope.modelNameFilter = this.workspaceService.metadata.model;
266 //check if property of VnfConfiguration
267 this.$scope.isVnfConfiguration = false;
268 if(this.propertyOwnerType == "component" && angular.isArray(this.compositionService.componentInstances)) {
269 const componentPropertyOwner:ComponentInstance = this.compositionService.componentInstances.find((ci:ComponentInstance) => {
270 return ci.uniqueId === this.property.resourceInstanceUniqueId;
272 if (componentPropertyOwner && componentPropertyOwner.componentName === 'vnfConfiguration') {
273 this.$scope.isVnfConfiguration = true;
277 this.initForNotSimpleType();
278 this.initComponentInstanceMap();
280 this.$scope.validateJson = (json:string):boolean => {
284 return this.ValidationUtils.validateJson(json);
287 this.DataTypesService.fetchDataTypesByModel(this.workspaceService.metadata.model).then(response => {
288 this.$scope.dataTypes = response.data as DataTypesMap;
289 this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
290 return this.$scope.editPropertyModel.types.indexOf(type) == -1;
293 this.$scope.isLoading = false;
297 this.$scope.save = (doNotCloseModal?:boolean):void => {
298 let property:PropertyModel = this.$scope.editPropertyModel.property;
299 this.$scope.editPropertyModel.property.description = this.ValidationUtils.stripAndSanitize(this.$scope.editPropertyModel.property.description);
300 //if read only - or no changes made - just closes the modal
301 //need to check for property.value changes manually to detect if map properties deleted
302 if ((this.$scope.editPropertyModel.property.readonly && !this.$scope.isPropertyValueOwner)
303 || (!this.$scope.forms.editForm.$dirty && angular.equals(JSON.stringify(this.$scope.myValue), this.$scope.editPropertyModel.property.value))) {
304 this.$uibModalInstance.close();
308 this.$scope.isLoading = true;
310 let onPropertyFailure = (response):void => {
311 console.error('Failed to update property', response);
312 this.$scope.isLoading = false;
315 let onPropertySuccess = (propertyFromBE:PropertyModel):void => {
316 this.$scope.isLoading = false;
317 this.filteredProperties[this.$scope.currentPropertyIndex] = propertyFromBE;
318 if (!doNotCloseModal) {
319 this.$uibModalInstance.close(propertyFromBE);
321 this.$scope.forms.editForm.$setPristine();
322 this.$scope.editPropertyModel.property = new PropertyModel();
326 //Not clean, but doing this as a temporary fix until we update the property right panel modals
327 if (this.propertyOwnerType === "group"){
328 this.ComponentInstanceServiceNg2.updateComponentGroupInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
329 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
330 } else if (this.propertyOwnerType === "policy"){
331 if (!this.$scope.editPropertyModel.property.simpleType &&
332 !this.$scope.isSimpleType(this.$scope.editPropertyModel.property.type) &&
333 !_.isNil(this.$scope.myValue)) {
334 property.value = JSON.stringify(this.$scope.myValue);
336 this.ComponentInstanceServiceNg2.updateComponentPolicyInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, this.propertyOwnerId, [property])
337 .subscribe((propertiesFromBE) => { onPropertySuccess(<PropertyModel>propertiesFromBE[0])}, error => onPropertyFailure(error));
339 //in case we have uniqueId we call update method
340 if (this.$scope.isPropertyValueOwner) {
341 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
342 property.value = JSON.stringify(this.$scope.myValue);
344 this.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).subscribe((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]),
345 error => onPropertyFailure(error));
347 if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
348 property.defaultValue = JSON.stringify(this.$scope.myValue);
350 this.$scope.editPropertyModel.property.defaultValue = this.$scope.editPropertyModel.property.value;
352 this.addOrUpdateProperty(property).subscribe(onPropertySuccess, error => onPropertyFailure(error));
357 this.$scope.getPrev = ():void=> {
358 this.property = this.filteredProperties[--this.$scope.currentPropertyIndex];
360 this.initForNotSimpleType();
361 this.$scope.isLastProperty = false;
364 this.$scope.getNext = ():void=> {
365 this.property = this.filteredProperties[++this.$scope.currentPropertyIndex];
367 this.initForNotSimpleType();
368 this.$scope.isLastProperty = this.$scope.currentPropertyIndex == (this.filteredProperties.length - 1);
371 this.$scope.isSimpleType = (typeName:string):boolean=> {
372 return typeName && this.$scope.editPropertyModel.simpleTypes.indexOf(typeName) != -1;
375 this.$scope.showSchema = ():boolean => {
376 return [PROPERTY_TYPES.LIST, PROPERTY_TYPES.MAP].indexOf(this.$scope.editPropertyModel.property.type) > -1;
379 this.$scope.getValidationPattern = (type:string):RegExp => {
380 return this.ValidationUtils.getValidationPattern(type);
383 this.$scope.validateIntRange = (value:string):boolean => {
384 return !value || this.ValidationUtils.validateIntRange(value);
387 this.$scope.close = ():void => {
388 this.$uibModalInstance.close();
391 // put default value when instance value is empty
392 this.$scope.onValueChange = ():void => {
393 if (!this.$scope.editPropertyModel.property.value) {
394 if (this.$scope.isPropertyValueOwner) {
395 this.$scope.editPropertyModel.property.value = this.$scope.editPropertyModel.property.defaultValue;
400 // Add the done button at the footer.
401 this.$scope.footerButtons = [
402 {'name': 'Save', 'css': 'blue', 'callback': this.$scope.save},
403 {'name': 'Cancel', 'css': 'grey', 'callback': this.$scope.close}
406 this.$scope.$watch("forms.editForm.$invalid", (newVal) => {
407 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
408 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
409 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
411 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
412 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
416 this.$scope.$watch("forms.editForm.$valid", (newVal) => {
417 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
418 this.$scope.invalidMandatoryFields = !newVal || !this.$scope.editPropertyModel.property.toscaFunction || this.isViewOnly;
419 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
421 this.$scope.invalidMandatoryFields = !newVal || this.isViewOnly;
422 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
426 this.$scope.getDefaultValue = ():any => {
427 return this.$scope.isPropertyValueOwner ? this.$scope.editPropertyModel.property.defaultValue : null;
430 this.$scope.onTypeChange = ():void => {
431 this.$scope.editPropertyModel.property.value = '';
432 this.$scope.editPropertyModel.property.defaultValue = '';
434 this.initForNotSimpleType();
437 this.$scope.onSchemaTypeChange = ():void => {
438 if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.MAP) {
439 this.$scope.myValue = {};
440 } else if (this.$scope.editPropertyModel.property.type == PROPERTY_TYPES.LIST) {
441 this.$scope.myValue = [];
446 this.$scope.delete = (property:PropertyModel):void => {
447 let onOk: Function = ():void => {
448 this.deleteProperty(property.uniqueId).subscribe(
452 let title:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TITLE");
453 let message:string = this.$filter('translate')("PROPERTY_VIEW_DELETE_MODAL_TEXT", "{'name': '" + property.name + "'}");
454 const okButton = {testId: "OK", text: "OK", type: SdcUiCommon.ButtonType.info, callback: onOk, closeModal: true} as SdcUiComponents.ModalButtonComponent;
455 this.modalService.openInfoModal(title, message, 'delete-modal', [okButton]);
458 this.$scope.onValueTypeChange = (): void => {
459 this.setEmptyValue();
460 if (this.$scope.editPropertyModel.hasGetFunctionValue) {
461 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
463 this.$scope.editPropertyModel.property.toscaFunction = undefined;
464 this.$scope.editPropertyModel.isGetFunctionValid = true;
468 this.$scope.onConstraintChange = (constraints: any): void => {
469 if (!this.$scope.invalidMandatoryFields) {
470 this.$scope.footerButtons[0].disabled = !constraints.valid;
472 this.$scope.footerButtons[0].disabled = this.$scope.invalidMandatoryFields;
474 if (!constraints.constraints || constraints.constraints.length == 0) {
475 this.$scope.editPropertyModel.property.propertyConstraints = null;
476 this.$scope.editPropertyModel.property.constraints = null;
479 this.$scope.editPropertyModel.property.propertyConstraints = this.serializePropertyConstraints(constraints.constraints);
480 this.$scope.editPropertyModel.property.constraints = constraints.constraints;
483 this.$scope.onGetFunctionValidFunction = (toscaGetFunction: ToscaGetFunction): void => {
484 this.$scope.editPropertyModel.property.toscaFunction = toscaGetFunction;
487 this.$scope.onToscaFunctionValidityChange = (validationEvent: ToscaFunctionValidationEvent): void => {
488 if (validationEvent.isValid) {
489 this.$scope.editPropertyModel.isGetFunctionValid = true;
492 this.$scope.editPropertyModel.isGetFunctionValid = undefined;
496 private serializePropertyConstraints(constraints: any[]): string[] {
498 let stringConstrsints = new Array();
499 constraints.forEach((constraint) => {
500 stringConstrsints.push(JSON.stringify(constraint));
502 return stringConstrsints;
507 private setEmptyValue() {
508 const property1 = this.$scope.editPropertyModel.property;
509 property1.value = undefined;
510 if (this.isComplexType(property1.type)) {
511 this.initEmptyComplexValue(property1.type);
514 this.$scope.myValue = '';
517 private updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):Observable<PropertyModel[]> => {
519 return this.ComponentInstanceServiceNg2.updateInstanceProperties(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, componentInstanceId, properties)
520 .map(newProperties => {
521 newProperties.forEach((newProperty) => {
522 if (!_.isNil(newProperty.path)) {
523 if (newProperty.path[0] === newProperty.resourceInstanceUniqueId) newProperty.path.shift();
524 // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
525 let existProperty: PropertyModel = <PropertyModel>_.find(this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
526 uniqueId: newProperty.uniqueId,
527 path: newProperty.path
529 let index = this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
530 this.compositionService.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
533 return newProperties;
537 private addOrUpdateProperty = (property: PropertyModel): Observable<PropertyModel> => {
538 if (!property.uniqueId) {
539 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
540 this.filteredProperties.push(newProperty);
543 return this.topologyTemplateService.addProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property)
546 let onSuccess = (newProperty: PropertyModel): PropertyModel => {
547 // find exist instance property in parent component for update the new value ( find bu uniqueId )
548 let existProperty: PropertyModel = <PropertyModel>_.find(this.filteredProperties, {uniqueId: newProperty.uniqueId});
549 let propertyIndex = this.filteredProperties.indexOf(existProperty);
550 this.filteredProperties[propertyIndex] = newProperty;
553 return this.topologyTemplateService.updateProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, property).map(onSuccess);
557 public deleteProperty = (propertyId:string):Observable<void> => {
558 let onSuccess = ():void => {
559 console.debug("Property deleted");
560 delete _.remove(this.filteredProperties, {uniqueId: propertyId})[0];
562 let onFailed = ():void => {
563 console.debug("Failed to delete property");
565 return this.topologyTemplateService.deleteProperty(this.workspaceService.metadata.componentType, this.workspaceService.metadata.uniqueId, propertyId).map(onSuccess, onFailed);