Merge from ecomp 718fd196 - Modern UI
[vid.git] / vid-webpack-master / src / app / shared / services / aaiService / aai.service.ts
1 import {NgRedux} from "@angular-redux/store";
2 import {HttpClient} from '@angular/common/http';
3 import {Injectable} from '@angular/core';
4 import * as _ from 'lodash';
5 import 'rxjs/add/operator/catch';
6 import 'rxjs/add/operator/do';
7 import {of} from "rxjs";
8
9 import {AicZone} from "../../models/aicZone";
10 import {CategoryParams} from "../../models/categoryParams";
11 import {LcpRegion} from "../../models/lcpRegion";
12 import {LcpRegionsAndTenants} from "../../models/lcpRegionsAndTenants";
13 import {OwningEntity} from "../../models/owningEntity";
14 import {ProductFamily} from "../../models/productFamily";
15 import {Project} from "../../models/project";
16 import {SelectOption} from '../../models/selectOption';
17 import {ServiceType} from "../../models/serviceType";
18 import {Subscriber} from "../../models/subscriber";
19 import {Tenant} from "../../models/tenant";
20 import {Constants} from '../../utils/constants';
21 import {AppState} from "../../store/reducers";
22 import {GetAicZonesResponse} from "./responseInterfaces/getAicZonesResponseInterface";
23 import {GetCategoryParamsResponseInterface} from "./responseInterfaces/getCategoryParamsResponseInterface";
24 import {GetServicesResponseInterface} from "./responseInterfaces/getServicesResponseInterface";
25 import {GetSubDetailsResponse} from "./responseInterfaces/getSubDetailsResponseInterface";
26 import {GetSubscribersResponse} from "./responseInterfaces/getSubscribersResponseInterface";
27 import {Root} from "./model/crawledAaiService";
28 import {VnfInstance} from "../../models/vnfInstance";
29 import {VfModuleInstance} from "../../models/vfModuleInstance";
30 import {ServiceInstance} from "../../models/serviceInstance";
31 import {VfModuleMap} from "../../models/vfModulesMap";
32 import {
33   updateAicZones,
34   updateCategoryParameters,
35   updateLcpRegionsAndTenants,
36   updateServiceTypes,
37   updateSubscribers,
38   updateUserId
39 } from "../../storeUtil/utils/general/general.actions";
40 import {updateModel, createServiceInstance} from "../../storeUtil/utils/service/service.actions";
41 import {FeatureFlagsService, Features} from "../featureFlag/feature-flags.service";
42 import {VnfMember} from "../../models/VnfMember";
43 import {setOptionalMembersVnfGroupInstance} from "../../storeUtil/utils/vnfGroup/vnfGroup.actions";
44 import {Observable} from "rxjs";import {NetworkModalRow} from "../../../drawingBoard/service-planning/objectsToTree/models/vrf/vrfModal/networkStep/network.step.model";
45 import {VPNModalRow} from "../../../drawingBoard/service-planning/objectsToTree/models/vrf/vrfModal/vpnStep/vpn.step.model";
46
47 @Injectable()
48 export class AaiService {
49   constructor(private http: HttpClient, private store: NgRedux<AppState>, private featureFlagsService:FeatureFlagsService) {
50
51   }
52
53   getServiceModelById = (serviceModelId: string): Observable<any> => {
54     if (_.has(this.store.getState().service.serviceHierarchy, serviceModelId)) {
55       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.serviceHierarchy[serviceModelId])));
56     }
57     let pathQuery: string = Constants.Path.SERVICES_PATH + serviceModelId;
58     return this.http.get(pathQuery).map(res => res)
59       .do((res) => {
60         this.store.dispatch(updateModel(res));
61       });
62   };
63
64   getUserId = (): Observable<any> => {
65     return this.http.get("../../getuserID", {responseType: 'text'}).do((res) => this.store.dispatch(updateUserId(res)));
66   };
67
68
69   resolve = (root: Root, serviceInstance: ServiceInstance) => {
70     if (root.type === 'service-instance') {
71       serviceInstance.instanceName = root.name;
72       serviceInstance.orchStatus = root.orchestrationStatus;
73       serviceInstance.modelInavariantId = root.modelInvariantId;
74       for (let i = 0; i < root.children.length; i++) {
75         let child = root.children[i];
76         if (child.type === 'generic-vnf') {
77           let vnf = new VnfInstance();
78           vnf.originalName = child.name;
79           vnf.orchStatus = child.orchestrationStatus
80           if (child.children.length > 0) {
81             let vfModuleMap = new VfModuleMap();
82             for (let j = 0; j < child.children.length; j++) {
83               let child = root.children[i];
84               if (child.type === 'vf-module') {
85                 let vfModule = new VfModuleInstance();
86                 vfModule.instanceName = child.name;
87                 vfModule.orchStatus = child.orchestrationStatus;
88                 vfModuleMap.vfModules[child.name] = vfModule;
89               }
90             }
91             vnf.vfModules = {"a": vfModuleMap};
92           }
93           serviceInstance.vnfs[child.name] = vnf;
94
95         }
96       }
97
98     }
99   };
100
101
102   getCRAccordingToNetworkFunctionId = (networkCollectionFunction, cloudOwner, cloudRegionId) => {
103     return this.http.get('../../aai_get_instance_groups_by_cloudregion/' + cloudOwner + '/' + cloudRegionId + '/' + networkCollectionFunction)
104       .map(res => res).do((res) => console.log(res));
105   };
106
107   getCategoryParameters = (familyName): Observable<CategoryParams> => {
108     familyName = familyName || Constants.Path.PARAMETER_STANDARDIZATION_FAMILY;
109     let pathQuery: string = Constants.Path.GET_CATEGORY_PARAMETERS + "?familyName=" + familyName + "&r=" + Math.random();
110
111     return this.http.get<GetCategoryParamsResponseInterface>(pathQuery)
112       .map(this.categoryParametersResponseToProductAndOwningEntity)
113       .do(res => {
114         this.store.dispatch(updateCategoryParameters(res))
115       });
116   };
117
118
119   categoryParametersResponseToProductAndOwningEntity = (res: GetCategoryParamsResponseInterface): CategoryParams => {
120     if (res && res.categoryParameters) {
121       const owningEntityList = res.categoryParameters.owningEntity.map(owningEntity => new OwningEntity(owningEntity));
122       const projectList = res.categoryParameters.project.map(project => new Project(project));
123       const lineOfBusinessList = res.categoryParameters.lineOfBusiness.map(owningEntity => new SelectOption(owningEntity));
124       const platformList = res.categoryParameters.platform.map(platform => new SelectOption(platform));
125
126       return new CategoryParams(owningEntityList, projectList, lineOfBusinessList, platformList);
127     } else {
128       return new CategoryParams();
129     }
130   };
131
132   getProductFamilies = (): Observable<ProductFamily[]> => {
133
134     let pathQuery: string = Constants.Path.AAI_GET_SERVICES + Constants.Path.ASSIGN + Math.random();
135
136     return this.http.get<GetServicesResponseInterface>(pathQuery).map(res => res.service.map(service => new ProductFamily(service)));
137   };
138
139   getServices = (): Observable<GetServicesResponseInterface> => {
140     let pathQuery: string = Constants.Path.AAI_GET_SERVICES + Constants.Path.ASSIGN + Math.random();
141
142     return this.http.get<GetServicesResponseInterface>(pathQuery);
143   };
144
145   getSubscribers = (): Observable<Subscriber[]> => {
146
147     if (this.store.getState().service.subscribers) {
148       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.subscribers)));
149     }
150
151     let pathQuery: string = Constants.Path.AAI_GET_SUBSCRIBERS + Constants.Path.ASSIGN + Math.random();
152
153     return this.http.get<GetSubscribersResponse>(pathQuery).map(res =>
154       res.customer.map(subscriber => new Subscriber(subscriber))).do((res) => {
155       this.store.dispatch(updateSubscribers(res));
156     });
157   };
158
159   getAicZones = (): Observable<AicZone[]> => {
160     if (this.store.getState().service.aicZones) {
161       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.aicZones)));
162     }
163
164     let pathQuery: string = Constants.Path.AAI_GET_AIC_ZONES + Constants.Path.ASSIGN + Math.random();
165
166     return this.http.get<GetAicZonesResponse>(pathQuery).map(res =>
167       res.zone.map(aicZone => new AicZone(aicZone))).do((res) => {
168       this.store.dispatch(updateAicZones(res));
169     });
170   };
171
172   getLcpRegionsAndTenants = (globalCustomerId, serviceType): Observable<LcpRegionsAndTenants> => {
173
174     let pathQuery: string = Constants.Path.AAI_GET_TENANTS
175       + globalCustomerId + Constants.Path.FORWARD_SLASH + serviceType + Constants.Path.ASSIGN + Math.random();
176
177     console.log("AaiService:getSubscriptionServiceTypeList: globalCustomerId: "
178       + globalCustomerId);
179     if (globalCustomerId != null) {
180       return this.http.get(pathQuery)
181         .map(this.tenantResponseToLcpRegionsAndTenants).do((res) => {
182           this.store.dispatch(updateLcpRegionsAndTenants(res));
183         });
184     }
185   };
186
187   tenantResponseToLcpRegionsAndTenants = (cloudRegionTenantList): LcpRegionsAndTenants => {
188
189     const lcpRegionsTenantsMap = {};
190
191     const lcpRegionList = _.uniqBy(cloudRegionTenantList, 'cloudRegionID').map((cloudRegionTenant) => {
192       const cloudOwner:string = cloudRegionTenant["cloudOwner"];
193       const cloudRegionId:string = cloudRegionTenant["cloudRegionID"];
194       const name:string = this.extractLcpRegionName(cloudRegionId, cloudOwner);
195       const isPermitted:boolean = cloudRegionTenant["is-permitted"];
196       return new LcpRegion(cloudRegionId, name, isPermitted, cloudOwner);
197     });
198
199     lcpRegionList.forEach(region => {
200       lcpRegionsTenantsMap[region.id] = _.filter(cloudRegionTenantList, {'cloudRegionID': region.id})
201         .map((cloudRegionTenant) => {
202           return new Tenant(cloudRegionTenant)
203         });
204       const reducer = (accumulator, currentValue) => {
205         accumulator.isPermitted = accumulator.isPermitted || currentValue.isPermitted;
206
207         return accumulator;
208       };
209       region.isPermitted = lcpRegionsTenantsMap[region.id].reduce(reducer).isPermitted;
210     });
211
212     return new LcpRegionsAndTenants(lcpRegionList, lcpRegionsTenantsMap);
213   };
214
215   public extractLcpRegionName(cloudRegionId: string, cloudOwner: string):string {
216    return this.featureFlagsService.getFlagState(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST) ?
217       cloudRegionId+AaiService.formatCloudOwnerTrailer(cloudOwner) : cloudRegionId;
218   };
219
220   public static formatCloudOwnerTrailer(cloudOwner: string):string {
221     return " ("+ cloudOwner.trim().toLowerCase().replace(/^[^-]*-/, "").toUpperCase() + ")";
222   }
223
224   getServiceTypes = (subscriberId): Observable<ServiceType[]> => {
225
226     console.log("AaiService:getSubscriptionServiceTypeList: globalCustomerId: " + subscriberId);
227     if (_.has(this.store.getState().service.serviceTypes, subscriberId)) {
228       return of(<ServiceType[]> JSON.parse(JSON.stringify(this.store.getState().service.serviceTypes[subscriberId])));
229     }
230
231     return this.getSubscriberDetails(subscriberId)
232       .map(this.subDetailsResponseToServiceTypes)
233       .do((res) => {
234         this.store.dispatch(updateServiceTypes(res, subscriberId));
235       });
236   };
237
238   getSubscriberDetails = (subscriberId): Observable<GetSubDetailsResponse> => {
239     let pathQuery: string = Constants.Path.AAI_SUB_DETAILS_PATH + subscriberId + Constants.Path.ASSIGN + Math.random() + Constants.Path.AAI_OMIT_SERVICE_INSTANCES + true;
240
241     if (subscriberId != null) {
242       return this.http.get<GetSubDetailsResponse>(pathQuery);
243     }
244   };
245
246   subDetailsResponseToServiceTypes = (res: GetSubDetailsResponse): ServiceType[] => {
247     if (res && res['service-subscriptions']) {
248       const serviceSubscriptions = res['service-subscriptions']['service-subscription'];
249       return serviceSubscriptions.map((subscription, index) => new ServiceType(String(index), subscription))
250     } else {
251       return [];
252     }
253   };
254
255
256   public retrieveServiceInstanceTopology(serviceInstanceId : string, subscriberId: string, serviceType: string):Observable<ServiceInstance> {
257     let pathQuery: string = `${Constants.Path.AAI_GET_SERVICE_INSTANCE_TOPOLOGY_PATH}${subscriberId}/${serviceType}/${serviceInstanceId}`;
258     return this.http.get<ServiceInstance>(pathQuery);
259   }
260
261   public retrieveActiveNetwork(cloudRegion : string, tenantId: string) : Observable<NetworkModalRow[]>{
262     let pathQuery: string = `${Constants.Path.AAI_GET_ACTIVE_NETWORKS_PATH}?cloudRegion=${cloudRegion}&tenantId=${tenantId}`;
263     return this.http.get<NetworkModalRow[]>(pathQuery);
264   }
265
266   public retrieveActiveVPNs() : Observable<VPNModalRow[]>{
267     let pathQuery: string = `${Constants.Path.AAI_GET_VPNS_PATH}`;
268     return this.http.get<VPNModalRow[]>(pathQuery);
269   }
270
271   public retrieveAndStoreServiceInstanceTopology(serviceInstanceId: string, subscriberId: string, serviceType: string, serviceModeId: string):Observable<ServiceInstance> {
272     return this.retrieveServiceInstanceTopology(serviceInstanceId, subscriberId, serviceType).do((service:ServiceInstance) => {
273       this.store.dispatch(createServiceInstance(service, serviceModeId));
274       });
275   };
276
277
278   public retrieveServiceInstanceRetryTopology(jobId : string) :Observable<ServiceInstance> {
279     let pathQuery: string = `${Constants.Path.SERVICES_RETRY_TOPOLOGY}/${jobId}`;
280     return this.http.get<ServiceInstance>(pathQuery);
281
282   }
283
284   public retrieveAndStoreServiceInstanceRetryTopology(jobId: string, serviceModeId : string):Observable<ServiceInstance> {
285     return this.retrieveServiceInstanceRetryTopology(jobId).do((service:ServiceInstance) => {
286       this.store.dispatch(createServiceInstance(service, serviceModeId));
287     });
288   };
289
290   public getOptionalGroupMembers(serviceModelId: string, subscriberId: string, serviceType: string, serviceInvariantId: string, groupType: string, groupRole: string): Observable<VnfMember[]> {
291     let pathQuery: string = `${Constants.Path.AAI_GET_SERVICE_GROUP_MEMBERS_PATH}${subscriberId}/${serviceType}/${serviceInvariantId}/${groupType}/${groupRole}`;
292     if(_.has(this.store.getState().service.serviceInstance[serviceModelId].optionalGroupMembersMap,pathQuery)){
293       return of(<VnfMember[]> JSON.parse(JSON.stringify(this.store.getState().service.serviceInstance[serviceModelId].optionalGroupMembersMap[pathQuery])));
294     }
295     return this.http.get<VnfMember[]>(pathQuery)
296       .do((res) => {
297         this.store.dispatch(setOptionalMembersVnfGroupInstance(serviceModelId, pathQuery, res))
298       });
299     // let res = Observable.of((JSON.parse(JSON.stringify(this.loadMockMembers()))));
300     // return  res;
301      
302   }
303
304   //TODO: make other places use this function
305   extractSubscriberNameBySubscriberId(subscriberId: string) {
306     let result: string = null;
307     let filteredArray: any = _.filter(this.store.getState().service.subscribers, function (o: Subscriber) {
308       return o.id === subscriberId
309     });
310     if (filteredArray.length > 0) {
311       result = filteredArray[0].name;
312     }
313     return result;
314   }
315
316   loadMockMembers(): any {
317     return [
318       {
319         "action":"None",
320         "instanceName":"VNF1_INSTANCE_NAME",
321         "instanceId":"VNF1_INSTANCE_ID",
322         "orchStatus":null,
323         "productFamilyId":null,
324         "lcpCloudRegionId":"hvf23b",
325         "tenantId":"3e9a20a3e89e45f884e09df0cc2d2d2a",
326         "tenantName":"APPC-24595-T-IST-02C",
327         "modelInfo":{
328           "modelInvariantId":"vnf-instance-model-invariant-id",
329           "modelVersionId":"7a6ee536-f052-46fa-aa7e-2fca9d674c44",
330           "modelVersion":"2.0",
331           "modelName":"vf_vEPDG",
332           "modelType":"vnf"
333         },
334         "instanceType":"VNF1_INSTANCE_TYPE",
335         "provStatus":null,
336         "inMaint":false,
337         "uuid":"7a6ee536-f052-46fa-aa7e-2fca9d674c44",
338         "originalName":null,
339         "legacyRegion":null,
340         "lineOfBusiness":null,
341         "platformName":null,
342         "trackById":"7a6ee536-f052-46fa-aa7e-2fca9d674c44:002",
343         "serviceInstanceId":"service-instance-id1",
344         "serviceInstanceName":"service-instance-name"
345       },
346       {
347         "action":"None",
348         "instanceName":"VNF2_INSTANCE_NAME",
349         "instanceId":"VNF2_INSTANCE_ID",
350         "orchStatus":null,
351         "productFamilyId":null,
352         "lcpCloudRegionId":"hvf23b",
353         "tenantId":"3e9a20a3e89e45f884e09df0cc2d2d2a",
354         "tenantName":"APPC-24595-T-IST-02C",
355         "modelInfo":{
356           "modelInvariantId":"vnf-instance-model-invariant-id",
357           "modelVersionId":"eb5f56bf-5855-4e61-bd00-3e19a953bf02",
358           "modelVersion":"1.0",
359           "modelName":"vf_vEPDG",
360           "modelType":"vnf"
361         },
362         "instanceType":"VNF2_INSTANCE_TYPE",
363         "provStatus":null,
364         "inMaint":true,
365         "uuid":"eb5f56bf-5855-4e61-bd00-3e19a953bf02",
366         "originalName":null,
367         "legacyRegion":null,
368         "lineOfBusiness":null,
369         "platformName":null,
370         "trackById":"eb5f56bf-5855-4e61-bd00-3e19a953bf02:003",
371         "serviceInstanceId":"service-instance-id2",
372         "serviceInstanceName":"service-instance-name"
373       }
374     ]
375
376   }
377
378
379 }