Merge "upgrade vfmodule when upgraded already service, vnf and brother vfmodule e2e"
[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 {Observable, 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 {createServiceInstance, updateModel,} 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 {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 import {ModelInfo} from "../../models/modelInfo";
47
48 @Injectable()
49 export class AaiService {
50   constructor(private http: HttpClient, private store: NgRedux<AppState>, private featureFlagsService:FeatureFlagsService) {
51
52   }
53
54   sdncPreload(): Observable<boolean> {
55     let pathQuery: string = Constants.Path.PRE_LOAD;
56     return this.http.post<boolean>(pathQuery, {})
57   }
58
59   getServiceModelById = (serviceModelId: string): Observable<any> => {
60     if (_.has(this.store.getState().service.serviceHierarchy, serviceModelId)) {
61       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.serviceHierarchy[serviceModelId])));
62     }
63     let pathQuery: string = Constants.Path.SERVICES_PATH + serviceModelId;
64     return this.http.get(pathQuery).map(res => res)
65       .do((res) => {
66         this.store.dispatch(updateModel(res));
67       });
68   };
69
70   retrieveServiceLatestUpdateableVersion = (modelInvariantId: string): Observable<ModelInfo> => {
71     let pathQuery: string = Constants.Path.SERVICE_LATEST_VERSION + modelInvariantId;
72     return this.http.get<ModelInfo>(pathQuery)
73   };
74
75   getUserId = (): Observable<any> => {
76     return this.http.get("../../getuserID", {responseType: 'text'}).do((res) => this.store.dispatch(updateUserId(res)));
77   };
78
79
80   resolve = (root: Root, serviceInstance: ServiceInstance) => {
81     if (root.type === 'service-instance') {
82       serviceInstance.instanceName = root.name;
83       serviceInstance.orchStatus = root.orchestrationStatus;
84       serviceInstance.modelInavariantId = root.modelInvariantId;
85       for (let i = 0; i < root.children.length; i++) {
86         let child = root.children[i];
87         if (child.type === 'generic-vnf') {
88           let vnf = new VnfInstance();
89           vnf.originalName = child.name;
90           vnf.orchStatus = child.orchestrationStatus
91           if (child.children.length > 0) {
92             let vfModuleMap = new VfModuleMap();
93             for (let j = 0; j < child.children.length; j++) {
94               let child = root.children[i];
95               if (child.type === 'vf-module') {
96                 let vfModule = new VfModuleInstance();
97                 vfModule.instanceName = child.name;
98                 vfModule.orchStatus = child.orchestrationStatus;
99                 vfModuleMap.vfModules[child.name] = vfModule;
100               }
101             }
102             vnf.vfModules = {"a": vfModuleMap};
103           }
104           serviceInstance.vnfs[child.name] = vnf;
105
106         }
107       }
108
109     }
110   };
111
112
113   getCRAccordingToNetworkFunctionId = (networkCollectionFunction, cloudOwner, cloudRegionId) => {
114     return this.http.get('../../aai_get_instance_groups_by_cloudregion/' + cloudOwner + '/' + cloudRegionId + '/' + networkCollectionFunction)
115       .map(res => res).do((res) => console.log(res));
116   };
117
118   getCategoryParameters = (familyName): Observable<CategoryParams> => {
119     familyName = familyName || Constants.Path.PARAMETER_STANDARDIZATION_FAMILY;
120     let pathQuery: string = Constants.Path.GET_CATEGORY_PARAMETERS + "?familyName=" + familyName + "&r=" + Math.random();
121
122     return this.http.get<GetCategoryParamsResponseInterface>(pathQuery)
123       .map(this.categoryParametersResponseToProductAndOwningEntity)
124       .do(res => {
125         this.store.dispatch(updateCategoryParameters(res))
126       });
127   };
128
129
130   categoryParametersResponseToProductAndOwningEntity = (res: GetCategoryParamsResponseInterface): CategoryParams => {
131     if (res && res.categoryParameters) {
132       const owningEntityList = res.categoryParameters.owningEntity.map(owningEntity => new OwningEntity(owningEntity));
133       const projectList = res.categoryParameters.project.map(project => new Project(project));
134       const lineOfBusinessList = res.categoryParameters.lineOfBusiness.map(owningEntity => new SelectOption(owningEntity));
135       const platformList = res.categoryParameters.platform.map(platform => new SelectOption(platform));
136
137       return new CategoryParams(owningEntityList, projectList, lineOfBusinessList, platformList);
138     } else {
139       return new CategoryParams();
140     }
141   };
142
143   getProductFamilies = (): Observable<ProductFamily[]> => {
144
145     let pathQuery: string = Constants.Path.AAI_GET_SERVICES + Constants.Path.ASSIGN + Math.random();
146
147     return this.http.get<GetServicesResponseInterface>(pathQuery).map(res => res.service.map(service => new ProductFamily(service)));
148   };
149
150   getServices = (): Observable<GetServicesResponseInterface> => {
151     let pathQuery: string = Constants.Path.AAI_GET_SERVICES + Constants.Path.ASSIGN + Math.random();
152
153     return this.http.get<GetServicesResponseInterface>(pathQuery);
154   };
155
156   getSubscribers = (): Observable<Subscriber[]> => {
157
158     if (this.store.getState().service.subscribers) {
159       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.subscribers)));
160     }
161
162     let pathQuery: string = Constants.Path.AAI_GET_SUBSCRIBERS + Constants.Path.ASSIGN + Math.random();
163
164     return this.http.get<GetSubscribersResponse>(pathQuery).map(res =>
165       res.customer.map(subscriber => new Subscriber(subscriber))).do((res) => {
166       this.store.dispatch(updateSubscribers(res));
167     });
168   };
169
170   getAicZones = (): Observable<AicZone[]> => {
171     if (this.store.getState().service.aicZones) {
172       return of(<any> JSON.parse(JSON.stringify(this.store.getState().service.aicZones)));
173     }
174
175     let pathQuery: string = Constants.Path.AAI_GET_AIC_ZONES + Constants.Path.ASSIGN + Math.random();
176
177     return this.http.get<GetAicZonesResponse>(pathQuery).map(res =>
178       res.zone.map(aicZone => new AicZone(aicZone))).do((res) => {
179       this.store.dispatch(updateAicZones(res));
180     });
181   };
182
183   getLcpRegionsAndTenants = (globalCustomerId, serviceType): Observable<LcpRegionsAndTenants> => {
184
185     let pathQuery: string = Constants.Path.AAI_GET_TENANTS
186       + globalCustomerId + Constants.Path.FORWARD_SLASH + serviceType + Constants.Path.ASSIGN + Math.random();
187
188     console.log("AaiService:getSubscriptionServiceTypeList: globalCustomerId: "
189       + globalCustomerId);
190     if (globalCustomerId != null) {
191       return this.http.get(pathQuery)
192         .map(this.tenantResponseToLcpRegionsAndTenants).do((res) => {
193           this.store.dispatch(updateLcpRegionsAndTenants(res));
194         });
195     }
196   };
197
198   tenantResponseToLcpRegionsAndTenants = (cloudRegionTenantList): LcpRegionsAndTenants => {
199
200     const lcpRegionsTenantsMap = {};
201
202     const lcpRegionList = _.uniqBy(cloudRegionTenantList, 'cloudRegionID').map((cloudRegionTenant) => {
203       const cloudOwner:string = cloudRegionTenant["cloudOwner"];
204       const cloudRegionId:string = cloudRegionTenant["cloudRegionID"];
205       const name:string = this.extractLcpRegionName(cloudRegionId, cloudOwner);
206       const isPermitted:boolean = cloudRegionTenant["is-permitted"];
207       return new LcpRegion(cloudRegionId, name, isPermitted, cloudOwner);
208     });
209
210     lcpRegionList.forEach(region => {
211       lcpRegionsTenantsMap[region.id] = _.filter(cloudRegionTenantList, {'cloudRegionID': region.id})
212         .map((cloudRegionTenant) => {
213           return new Tenant(cloudRegionTenant)
214         });
215       const reducer = (accumulator, currentValue) => {
216         accumulator.isPermitted = accumulator.isPermitted || currentValue.isPermitted;
217
218         return accumulator;
219       };
220       region.isPermitted = lcpRegionsTenantsMap[region.id].reduce(reducer).isPermitted;
221     });
222
223     return new LcpRegionsAndTenants(lcpRegionList, lcpRegionsTenantsMap);
224   };
225
226   public extractLcpRegionName(cloudRegionId: string, cloudOwner: string):string {
227     return this.featureFlagsService.getFlagState(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST) ?
228       cloudRegionId+AaiService.formatCloudOwnerTrailer(cloudOwner) : cloudRegionId;
229   };
230
231
232
233
234
235   getLcpRegionsByOwningEntityAndLineOfBusiness = (owningEntityName, lineOfBusinessName): Observable<LcpRegion[]> => {
236     // let pathQuery: string = Constants.Path.AAI_GET_LCP_REGIONS_BY____
237     //   + "?"
238     //   + "owningEntityName=" + owningEntityName
239     //   + "lineOfBusinessName=" + lineOfBusinessName;
240
241     return of([
242       new LcpRegion("foo-id", "foo-name", true, "foo-cloud-owner"),
243       new LcpRegion("foo2-id", "foo2-name", true, "foo2-cloud-owner"),
244     ]);
245   };
246
247
248   getTenantsByCloudOwnerAndCloudRegionId = (cloudOwner, cloudRegionId): Observable<Tenant[]> => {
249     // let pathQuery: string = Constants.Path.AAI_GET_TENANTS_BY____
250     //   + "?"
251     //   + "cloudOwner=" + cloudOwner
252     //   + "&cloudRegionId=" + cloudRegionId;
253
254     return of([
255       new Tenant({
256         tenantID: "tenantID", tenantName: "tenantName",
257         cloudOwner: "cloudOwner", ['is-permitted']: true,
258       }),
259       new Tenant({
260         tenantID: "tenant2ID", tenantName: "tenant2Name",
261         cloudOwner: "cloudOwner", ['is-permitted']: true,
262       }),
263     ])
264   };
265
266
267
268
269
270   public static formatCloudOwnerTrailer(cloudOwner: string):string {
271     return " ("+ cloudOwner.trim().toLowerCase().replace(/^[^-]*-/, "").toUpperCase() + ")";
272   }
273
274   getServiceTypes = (subscriberId): Observable<ServiceType[]> => {
275
276     console.log("AaiService:getSubscriptionServiceTypeList: globalCustomerId: " + subscriberId);
277     if (_.has(this.store.getState().service.serviceTypes, subscriberId)) {
278       return of(<ServiceType[]> JSON.parse(JSON.stringify(this.store.getState().service.serviceTypes[subscriberId])));
279     }
280
281     return this.getSubscriberDetails(subscriberId)
282       .map(this.subDetailsResponseToServiceTypes)
283       .do((res) => {
284         this.store.dispatch(updateServiceTypes(res, subscriberId));
285       });
286   };
287
288   getSubscriberDetails = (subscriberId): Observable<GetSubDetailsResponse> => {
289     let pathQuery: string = Constants.Path.AAI_SUB_DETAILS_PATH + subscriberId + Constants.Path.ASSIGN + Math.random() + Constants.Path.AAI_OMIT_SERVICE_INSTANCES + true;
290
291     if (subscriberId != null) {
292       return this.http.get<GetSubDetailsResponse>(pathQuery);
293     }
294   };
295
296   subDetailsResponseToServiceTypes = (res: GetSubDetailsResponse): ServiceType[] => {
297     if (res && res['service-subscriptions']) {
298       const serviceSubscriptions = res['service-subscriptions']['service-subscription'];
299       return serviceSubscriptions.map((subscription, index) => new ServiceType(String(index), subscription))
300     } else {
301       return [];
302     }
303   };
304
305
306   public retrieveServiceInstanceTopology(serviceInstanceId : string, subscriberId: string, serviceType: string):Observable<ServiceInstance> {
307     let pathQuery: string = `${Constants.Path.AAI_GET_SERVICE_INSTANCE_TOPOLOGY_PATH}${subscriberId}/${serviceType}/${serviceInstanceId}`;
308     return this.http.get<ServiceInstance>(pathQuery);
309   }
310
311   public retrieveActiveNetwork(cloudRegion : string, tenantId: string) : Observable<NetworkModalRow[]>{
312     let pathQuery: string = `${Constants.Path.AAI_GET_ACTIVE_NETWORKS_PATH}?cloudRegion=${cloudRegion}&tenantId=${tenantId}`;
313     return this.http.get<NetworkModalRow[]>(pathQuery);
314   }
315
316   public retrieveActiveVPNs() : Observable<VPNModalRow[]>{
317     let pathQuery: string = `${Constants.Path.AAI_GET_VPNS_PATH}`;
318     return this.http.get<VPNModalRow[]>(pathQuery);
319   }
320
321   public retrieveAndStoreServiceInstanceTopology(serviceInstanceId: string, subscriberId: string, serviceType: string, serviceModeId: string):Observable<ServiceInstance> {
322     return this.retrieveServiceInstanceTopology(serviceInstanceId, subscriberId, serviceType).do((service:ServiceInstance) => {
323       this.store.dispatch(createServiceInstance(service, serviceModeId));
324     });
325   };
326
327
328   public retrieveServiceInstanceRetryTopology(jobId : string) :Observable<ServiceInstance> {
329     let pathQuery: string = `${Constants.Path.SERVICES_RETRY_TOPOLOGY}/${jobId}`;
330     return this.http.get<ServiceInstance>(pathQuery);
331
332   }
333
334   public retrieveAndStoreServiceInstanceRetryTopology(jobId: string, serviceModeId : string):Observable<ServiceInstance> {
335     return this.retrieveServiceInstanceRetryTopology(jobId).do((service:ServiceInstance) => {
336       this.store.dispatch(createServiceInstance(service, serviceModeId));
337     });
338   };
339
340   public getOptionalGroupMembers(serviceModelId: string, subscriberId: string, serviceType: string, serviceInvariantId: string, groupType: string, groupRole: string): Observable<VnfMember[]> {
341     let pathQuery: string = `${Constants.Path.AAI_GET_SERVICE_GROUP_MEMBERS_PATH}${subscriberId}/${serviceType}/${serviceInvariantId}/${groupType}/${groupRole}`;
342     if(_.has(this.store.getState().service.serviceInstance[serviceModelId].optionalGroupMembersMap,pathQuery)){
343       return of(<VnfMember[]> JSON.parse(JSON.stringify(this.store.getState().service.serviceInstance[serviceModelId].optionalGroupMembersMap[pathQuery])));
344     }
345     return this.http.get<VnfMember[]>(pathQuery)
346       .do((res) => {
347         this.store.dispatch(setOptionalMembersVnfGroupInstance(serviceModelId, pathQuery, res))
348       });
349   }
350
351   //TODO: make other places use this function
352   extractSubscriberNameBySubscriberId(subscriberId: string) {
353     let result: string = null;
354     let filteredArray: any = _.filter(this.store.getState().service.subscribers, function (o: Subscriber) {
355       return o.id === subscriberId
356     });
357     if (filteredArray.length > 0) {
358       result = filteredArray[0].name;
359     }
360     return result;
361   }
362
363   loadMockMembers(): any {
364     return [
365       {
366         "action":"None",
367         "instanceName":"VNF1_INSTANCE_NAME",
368         "instanceId":"VNF1_INSTANCE_ID",
369         "orchStatus":null,
370         "productFamilyId":null,
371         "lcpCloudRegionId":"hvf23b",
372         "tenantId":"3e9a20a3e89e45f884e09df0cc2d2d2a",
373         "tenantName":"APPC-24595-T-IST-02C",
374         "modelInfo":{
375           "modelInvariantId":"vnf-instance-model-invariant-id",
376           "modelVersionId":"7a6ee536-f052-46fa-aa7e-2fca9d674c44",
377           "modelVersion":"2.0",
378           "modelName":"vf_vEPDG",
379           "modelType":"vnf"
380         },
381         "instanceType":"VNF1_INSTANCE_TYPE",
382         "provStatus":null,
383         "inMaint":false,
384         "uuid":"7a6ee536-f052-46fa-aa7e-2fca9d674c44",
385         "originalName":null,
386         "legacyRegion":null,
387         "lineOfBusiness":null,
388         "platformName":null,
389         "trackById":"7a6ee536-f052-46fa-aa7e-2fca9d674c44:002",
390         "serviceInstanceId":"service-instance-id1",
391         "serviceInstanceName":"service-instance-name"
392       },
393       {
394         "action":"None",
395         "instanceName":"VNF2_INSTANCE_NAME",
396         "instanceId":"VNF2_INSTANCE_ID",
397         "orchStatus":null,
398         "productFamilyId":null,
399         "lcpCloudRegionId":"hvf23b",
400         "tenantId":"3e9a20a3e89e45f884e09df0cc2d2d2a",
401         "tenantName":"APPC-24595-T-IST-02C",
402         "modelInfo":{
403           "modelInvariantId":"vnf-instance-model-invariant-id",
404           "modelVersionId":"eb5f56bf-5855-4e61-bd00-3e19a953bf02",
405           "modelVersion":"1.0",
406           "modelName":"vf_vEPDG",
407           "modelType":"vnf"
408         },
409         "instanceType":"VNF2_INSTANCE_TYPE",
410         "provStatus":null,
411         "inMaint":true,
412         "uuid":"eb5f56bf-5855-4e61-bd00-3e19a953bf02",
413         "originalName":null,
414         "legacyRegion":null,
415         "lineOfBusiness":null,
416         "platformName":null,
417         "trackById":"eb5f56bf-5855-4e61-bd00-3e19a953bf02:003",
418         "serviceInstanceId":"service-instance-id2",
419         "serviceInstanceName":"service-instance-name"
420       }
421     ]
422
423   }
424
425
426 }