Constraints in data type view
[sdc.git] / catalog-ui / src / app / ng2 / services / data-type.service.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 import * as _ from "lodash";
22 import {Inject, Injectable} from '@angular/core';
23 import {DataTypeModel, DataTypesMap, PropertyFEModel, DerivedFEProperty, PropertyBEModel} from "app/models";
24 import { DataTypesService } from "app/services/data-types-service";
25 import { PROPERTY_DATA } from "app/utils";
26 import {DerivedFEAttribute} from "../../models/attributes-outputs/derived-fe-attribute";
27 import {ISdcConfig} from "../config/sdc-config.config.factory";
28 import {SdcConfigToken} from "../config/sdc-config.config";
29 import {HttpBackend, HttpClient, HttpHeaders} from "@angular/common/http";
30 import {Observable} from "rxjs/Observable";
31 import {AuthenticationService} from "./authentication.service";
32
33 /** This is a new service for NG2, to eventually replace app/services/data-types-service.ts
34  *
35  *  This service is a singleton that holds a map of all DataTypes, recieved from server on load.
36  *  It also contains convenience methods to check if a string is a valid dataType, and to retrieve a dataType's properties recursively
37  */
38
39 @Injectable()
40 export class DataTypeService {
41     public dataTypes: DataTypesMap;
42     private readonly baseUrl: string;
43     private readonly dataTypeUrl: string;
44     private readonly dataTypeUploadUrl: string;
45
46
47     constructor(private dataTypeService: DataTypesService, private authService: AuthenticationService, private handler: HttpBackend, private httpClient: HttpClient, @Inject(SdcConfigToken) sdcConfig: ISdcConfig) {
48         this.dataTypes = dataTypeService.getAllDataTypes(); //This should eventually be replaced by an NG2 call to the backend instead of utilizing Angular1 downgraded component.
49         this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root;
50         this.dataTypeUrl = `${this.baseUrl}data-types`;
51         this.dataTypeUploadUrl = `${this.baseUrl}uploadType`;
52         this.httpClient = new HttpClient(handler);
53     }
54
55     public getDataTypeByModelAndTypeName(modelName: string, typeName: string): DataTypeModel {
56         this.dataTypes = this.dataTypeService.getAllDataTypesFromModel(modelName);
57         let dataTypeFound = this.dataTypes[typeName];
58         if (!dataTypeFound) {
59             console.log("MISSING Datatype for model " + modelName + " and type: " + typeName);
60         }
61         return dataTypeFound;
62     }
63
64     public getDataTypeByTypeName(typeName: string): DataTypeModel {
65         if(!this.dataTypes){
66             this.dataTypes = this.dataTypeService.getAllDataTypes();
67         }
68         if (!this.dataTypes[typeName]) console.log("MISSING Datatype: " + typeName);
69         return this.dataTypes[typeName];
70     }
71
72     public getDataTypeByModel(modelName: string): DataTypesMap {
73         return this.dataTypeService.getAllDataTypesFromModel(modelName);
74     }
75
76     public findAllDataTypesByModel(modelName: string): Promise<Map<string, DataTypeModel>> {
77         return this.dataTypeService.findAllDataTypesByModel(modelName);
78     }
79
80     public findById(id: string): Observable<DataTypeModel> {
81         const url = `${this.dataTypeUrl}/${id}`
82         return this.httpClient.get<DataTypeModel>(url);
83     }
84
85     public findAllProperties(id: string): Observable<Array<PropertyBEModel>> {
86         const url = `${this.dataTypeUrl}/${id}/properties`
87         return this.httpClient.get<Array<PropertyBEModel>>(url);
88     }
89
90     public createProperty(id: string, property: PropertyBEModel): Observable<PropertyBEModel> {
91         const url = `${this.dataTypeUrl}/${id}/properties`;
92         return this.httpClient.post<PropertyBEModel>(url, property);
93     }
94
95     public createImportedType(model: string, importingFile: File): Observable<any> {
96         const url = `${this.dataTypeUploadUrl}/datatypesyaml`;
97         const formData = new FormData();
98         formData.append('dataTypesYaml', importingFile);
99         formData.append('model', model != 'SDC AID' ? model : "")
100         formData.append('includeToModelImport', "true");
101         let headers = new HttpHeaders({'USER_ID': this.authService.getLoggedinUser().userId});
102         let options = {headers: headers};
103
104         return this.httpClient.post<any>(url, formData, options);
105     }
106
107     public getConstraintsByParentTypeAndUniqueID(rootPropertyType, propertyName){
108         // const property = this.dataTypes[rootPropertyType].properties.filter(property =>
109         //     property.name == propertyName);
110         // return property[0] && property[0].constraints ? property[0].constraints[0].validValues : null;
111         return null;
112     }
113
114     public getDerivedDataTypeProperties(dataTypeObj: DataTypeModel, propertiesArray: Array<DerivedFEProperty>, parentName: string) {
115         //push all child properties to array
116         if (!dataTypeObj) return;
117         if (dataTypeObj.properties) {
118             dataTypeObj.properties.forEach((derivedProperty) => {
119                 if(dataTypeObj.name !== PROPERTY_DATA.OPENECOMP_ROOT || derivedProperty.name !== PROPERTY_DATA.SUPPLEMENTAL_DATA){//The requirement is to not display the property supplemental_data
120                     propertiesArray.push(new DerivedFEProperty(derivedProperty, parentName));
121                 }
122                 let derivedDataTypeObj: DataTypeModel = this.getDataTypeByTypeName(derivedProperty.type);
123                 this.getDerivedDataTypeProperties(derivedDataTypeObj, propertiesArray, parentName + "#" + derivedProperty.name);
124             });
125         }
126         //recurse parent (derivedFrom), in case one of parents contains properties
127         if (dataTypeObj.derivedFrom && PROPERTY_DATA.ROOT_DATA_TYPE !== dataTypeObj.derivedFrom.name) {
128             this.getDerivedDataTypeProperties(dataTypeObj.derivedFrom, propertiesArray, parentName);
129         }
130     }
131
132     public getDerivedDataTypeAttributes(dataTypeObj: DataTypeModel, attributesArray: Array<DerivedFEAttribute>, parentName: string) {
133         //push all child properties to array
134         if (!dataTypeObj) return;
135         if (dataTypeObj.attributes) {
136             dataTypeObj.attributes.forEach((derivedAttribute) => {
137                 if(dataTypeObj.name !== PROPERTY_DATA.OPENECOMP_ROOT || derivedAttribute.name !== PROPERTY_DATA.SUPPLEMENTAL_DATA){//The requirement is to not display the property supplemental_data
138                     attributesArray.push(new DerivedFEAttribute(derivedAttribute, parentName));
139                 }
140                 let derivedDataTypeObj: DataTypeModel = this.getDataTypeByTypeName(derivedAttribute.type);
141                 this.getDerivedDataTypeAttributes(derivedDataTypeObj, attributesArray, parentName + "#" + derivedAttribute.name);
142             });
143         }
144         //recurse parent (derivedFrom), in case one of parents contains properties
145         if (dataTypeObj.derivedFrom && PROPERTY_DATA.ROOT_DATA_TYPE !== dataTypeObj.derivedFrom.name) {
146             this.getDerivedDataTypeAttributes(dataTypeObj.derivedFrom, attributesArray, parentName);
147         }
148     }
149
150     /**
151      * Checks for custom behavior for a given data type by checking if a function exists within data-type.service with that name
152      * Additional custom behavior can be added by adding a function with the given dataType name
153      */
154     public checkForCustomBehavior = (property:PropertyFEModel) => {
155         let shortTypeName:string = property.type.split('.').pop();
156         if (this[shortTypeName]) {
157             this[shortTypeName](property); //execute function for given type, pass property as param
158         }
159     }
160
161     public Naming = (property: PropertyFEModel) => {
162         let generatedNamingVal: boolean = _.get(property.valueObj, 'ecomp_generated_naming', true);
163         property.flattenedChildren.forEach((prop) => {
164             if (prop.name == 'naming_policy') prop.hidden = !generatedNamingVal;
165             if (prop.name == 'instance_name') prop.hidden = generatedNamingVal;
166         });
167     }
168 }
169