Angular upgrade
[osm/NG-UI.git] / src / app / instances / ns-primitive / NSPrimitiveComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17  */
18 /**
19  * @file NS Instance Primitive Component
20  */
21 import { Component, Injector, Input, OnInit } from '@angular/core';
22 import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
23 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { NotifierService } from 'angular-notifier';
26 import { APIURLHEADER, ERRORDATA, PRIMITIVEDATA, PRIMITIVETYPES, URLPARAMS } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { KDUPRIMITIVELEVEL, NSData, VDUPRIMITIVELEVEL, VNFPROFILE } from 'NSDModel';
30 import { NSPrimitiveParams } from 'NSInstanceModel';
31 import { RestService } from 'RestService';
32 import { SharedService, isNullOrUndefined } from 'SharedService';
33 import { CONFIGPRIMITIVE, DF, VDUCONFIG, VDUPROFILE, VNFCONFIG, VNFD } from 'VNFDModel';
34 import { VNFInstanceDetails } from 'VNFInstanceModel';
35
36 /**
37  * Creating component
38  * @Component takes NSPrimitiveComponent.html as template url
39  */
40 @Component({
41     templateUrl: './NSPrimitiveComponent.html',
42     styleUrls: ['./NSPrimitiveComponent.scss']
43 })
44 /** Exporting a class @exports NSPrimitiveComponent */
45 export class NSPrimitiveComponent implements OnInit {
46     /** Form valid on submit trigger @public */
47     public submitted: boolean = false;
48
49     /** To inject services @public */
50     public injector: Injector;
51
52     /** Instance for active modal service @public */
53     public activeModal: NgbActiveModal;
54
55     /** FormGroup instance added to the form @ html @public */
56     public primitiveForm: FormGroup;
57
58     /** Primitive params array @public */
59     public primitiveParams: FormArray;
60
61     /** Variable set for twoway binding @public */
62     public nsdId: string;
63
64     /** Check the loading results @public */
65     public isLoadingResults: boolean = false;
66
67     /** Give the message for the loading @public */
68     public message: string = 'PLEASEWAIT';
69
70     /** Contains list of primitive parameter @public */
71     public primitiveParameter: {}[] = [];
72
73     /** Input contains component objects @public */
74     @Input() public params: URLPARAMS;
75
76     /** Contains list of primitive actions @public */
77     public primitiveList: {}[];
78
79     /** Contains objects that is used to hold types of primitive @public */
80     public primitiveTypeList: PRIMITIVETYPES[] = [];
81
82     /** Model value used to hold selected primitive type @public */
83     public primitiveType: string;
84
85     /** Contains list of VDU primitive lists @public */
86     public vduList: VDUPROFILE[];
87
88     /** Contains list of KDU primitive lists @public */
89     public kduList: {}[];
90
91     /** Array holds MemberVNFIndex values @public */
92     public memberVnfIndex: {}[] = [];
93
94     /** Array holds VNFR Data filtered with nsr ID @public */
95     public nsIdFilteredData: {}[] = [];
96
97     /** Items for the memberVNFIndex data @public */
98     public memberTypes: {}[];
99
100     /** FormBuilder instance added to the formBuilder @private */
101     private formBuilder: FormBuilder;
102
103     /** Utilizes rest service for any CRUD operations @private */
104     private restService: RestService;
105
106     /** packages data service collections @private */
107     private dataService: DataService;
108
109     /** Contains tranlsate instance @private */
110     private translateService: TranslateService;
111
112     /** Notifier service to popup notification @private */
113     private notifierService: NotifierService;
114
115     /** Contains all methods related to shared @private */
116     private sharedService: SharedService;
117
118     /** Contains objects that is used to convert key/value pair @private */
119     private objectPrimitiveParams: {} = {};
120
121     constructor(injector: Injector) {
122         this.injector = injector;
123         this.restService = this.injector.get(RestService);
124         this.dataService = this.injector.get(DataService);
125         this.translateService = this.injector.get(TranslateService);
126         this.notifierService = this.injector.get(NotifierService);
127         this.sharedService = this.injector.get(SharedService);
128         this.activeModal = this.injector.get(NgbActiveModal);
129         this.formBuilder = this.injector.get(FormBuilder);
130         this.primitiveTypeList = [
131             {
132                 title: this.translateService.instant('NSPRIMITIVE'),
133                 value: 'NS_Primitive'
134             },
135             {
136                 title: this.translateService.instant('VNFPRIMITIVE'),
137                 value: 'VNF_Primitive'
138             },
139             {
140                 title: this.translateService.instant('VDUPRIMITIVE'),
141                 value: 'VDU_Primitive'
142             },
143             {
144                 title: this.translateService.instant('KDUPRIMITIVE'),
145                 value: 'KDU_Primitive'
146             }
147         ];
148     }
149
150     /** convenience getter for easy access to form fields */
151     get f(): FormGroup['controls'] { return this.primitiveForm.controls; }
152
153     /**
154      * Lifecyle Hooks the trigger before component is instantiate
155      */
156     public ngOnInit(): void {
157         /** Setting up initial value for NSD */
158         this.dataService.currentMessage.subscribe((event: NSData): void => {
159             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
160                 this.nsdId = event.identifier;
161             }
162         });
163         this.getMemberVnfIndex();
164         this.initializeForm();
165     }
166
167     /** initialize Forms @public */
168     public initializeForm(): void {
169         this.primitiveForm = this.formBuilder.group({
170             primitive: [null, [Validators.required]],
171             member_vnf_index: [null, [Validators.required]],
172             vdu_id: [null, [Validators.required]],
173             kdu_name: [null, [Validators.required]],
174             primitive_params: this.formBuilder.array([this.primitiveParamsBuilder()])
175         });
176     }
177
178     /** Generate primitive params @public */
179     public primitiveParamsBuilder(): FormGroup {
180         return this.formBuilder.group({
181             primitive_params_name: [null, [Validators.required]],
182             primitive_params_value: ['', [Validators.required]]
183         });
184     }
185
186     /** Handle FormArray Controls @public */
187     public getControls(): AbstractControl[] {
188         return (this.getFormControl('primitive_params') as FormArray).controls;
189     }
190
191     /** Push all primitive params on user's action @public */
192     public createPrimitiveParams(): void {
193         this.primitiveParams = this.getFormControl('primitive_params') as FormArray;
194         this.primitiveParams.push(this.primitiveParamsBuilder());
195     }
196
197     /** Remove primitive params on user's action @public */
198     public removePrimitiveParams(index: number): void {
199         this.primitiveParams.removeAt(index);
200     }
201
202     /** Execute Primitive @public */
203     public execPrimitive(): void {
204         this.submitted = true;
205         this.objectPrimitiveParams = {};
206         this.sharedService.cleanForm(this.primitiveForm);
207         if (this.primitiveForm.invalid) { return; } // Proceed, onces form is valid
208         this.primitiveForm.value.primitive_params.forEach((params: NSPrimitiveParams): void => {
209             if (params.primitive_params_name !== null && params.primitive_params_value !== '') {
210                 this.objectPrimitiveParams[params.primitive_params_name] = params.primitive_params_value;
211             }
212         });
213         //Prepare primitive params
214         const primitiveParamsPayLoads: {} = {
215             primitive: this.primitiveForm.value.primitive,
216             primitive_params: this.objectPrimitiveParams
217         };
218         if (this.primitiveType === 'VNF_Primitive') {
219             // eslint-disable-next-line @typescript-eslint/dot-notation
220             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
221         }
222         if (this.primitiveType === 'VDU_Primitive') {
223             // eslint-disable-next-line @typescript-eslint/dot-notation
224             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
225             // eslint-disable-next-line @typescript-eslint/dot-notation
226             primitiveParamsPayLoads['vdu_id'] = this.primitiveForm.value.vdu_id;
227         }
228         if (this.primitiveType === 'KDU_Primitive') {
229             // eslint-disable-next-line @typescript-eslint/dot-notation
230             primitiveParamsPayLoads['member_vnf_index'] = this.primitiveForm.value.member_vnf_index;
231             // eslint-disable-next-line @typescript-eslint/dot-notation
232             primitiveParamsPayLoads['kdu_name'] = this.primitiveForm.value.kdu_name;
233         }
234         const apiURLHeader: APIURLHEADER = {
235             url: environment.NSDINSTANCES_URL + '/' + this.nsdId + '/action'
236         };
237         this.isLoadingResults = true;
238         this.restService.postResource(apiURLHeader, primitiveParamsPayLoads).subscribe((result: {}): void => {
239             this.activeModal.dismiss();
240             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPRIMITIVE.EXECUTEDSUCCESSFULLY'));
241             this.isLoadingResults = false;
242         }, (error: ERRORDATA): void => {
243             this.isLoadingResults = false;
244             this.restService.handleError(error, 'post');
245         });
246     }
247     /** Getting MemberVnfIndex using VNFDescriptor API @public */
248     public getMemberVnfIndex(): void {
249         const vnfInstanceData: {}[] = [];
250         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
251             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
252                 const vnfDataObj: {} =
253                 {
254                     'vnf-ref': vnfData['vnfd-ref'],
255                     'vnf-id': vnfData._id,
256                     'member-index': vnfData['member-vnf-index-ref']
257                 };
258                 vnfInstanceData.push(vnfDataObj);
259             });
260             for (const id of this.params.id) {
261                 this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData['vnf-id'] === id);
262                 this.nsIdFilteredData.forEach((resVNF: {}[]): void => {
263                     const assignMemberIndex: {} = {
264                         id: resVNF['member-index'],
265                         'vnf-ref': resVNF['vnf-ref']
266                     };
267                     this.memberVnfIndex.push(assignMemberIndex);
268                 });
269             }
270             this.memberTypes = this.memberVnfIndex;
271             this.isLoadingResults = false;
272         }, (error: ERRORDATA): void => {
273             this.restService.handleError(error, 'get');
274             this.isLoadingResults = false;
275         });
276     }
277     /** Primitive type change event @public */
278     public primitiveTypeChange(data: PRIMITIVETYPES): void {
279         this.primitiveList = [];
280         this.primitiveParameter = [];
281         this.initializeForm();
282         if (data.value === 'NS_Primitive') {
283             this.getNSInfo(this.params.name);
284             this.setUpdateValueandValidation('member_vnf_index');
285         }
286         if (data.value === 'VNF_Primitive' || data.value === 'KDU_Primitive' || data.value === 'NS_Primitive') {
287             this.setUpdateValueandValidation('vdu_id');
288         }
289         if (data.value === 'VDU_Primitive' || data.value === 'VNF_Primitive' || data.value === 'NS_Primitive') {
290             this.setUpdateValueandValidation('kdu_name');
291         }
292     }
293     /** Member index change event */
294     public indexChange(data: VNFPROFILE, getType?: string): void {
295         this.getFormControl('vdu_id').setValue(null);
296         this.getFormControl('kdu_name').setValue(null);
297         if (data['vnf-ref'] !== null) {
298             this.getVnfdInfo(data['vnf-ref'], getType);
299         } else {
300             this.primitiveList = [];
301             this.getFormControl('primitive').setValue(null);
302             this.primitiveParameter = [];
303         }
304     }
305     /** Get VDU/KDU primitive List for the selected event @public */
306     public getPrimitiveList(data: {}, selectedType: string): void {
307         this.primitiveList = data[selectedType + '-configuration']['config-primitive'];
308     }
309     /** Primivtive change event */
310     public primitiveChange(data: PRIMITIVEDATA): void {
311         this.primitiveParameter = [];
312         const formArr: FormArray = this.getFormControl('primitive_params') as FormArray;
313         formArr.controls = [];
314         this.createPrimitiveParams();
315         if (data) {
316             this.updatePrimitive(data);
317         }
318     }
319     /** Generate vdu section @public */
320     public generateVDUData(vduConfig: VDUCONFIG): VDUPROFILE {
321         return {
322             id: vduConfig.id,
323             name: vduConfig.id,
324             'vdu-configuration': vduConfig
325         };
326     }
327     /** Generate kdu section @public */
328     public generateKDUData(kduData: KDUPRIMITIVELEVEL, kduConfig: VDUCONFIG): KDUPRIMITIVELEVEL {
329         return {
330             name: kduData.name,
331             'juju-bundle': kduData['juju-bundle'],
332             'kdu-configuration': kduConfig
333         };
334     }
335     /** Used to set the validation and value and update the validation and value @public */
336     public setUpdateValueandValidation(formName: string): void {
337         this.getFormControl(formName).setValidators([]);
338         this.getFormControl(formName).updateValueAndValidity();
339     }
340     /** Update primitive value based on parameter */
341     private updatePrimitive(primitive: PRIMITIVEDATA): void {
342         if (primitive.parameter) {
343             this.primitiveParameter = primitive.parameter;
344         } else {
345             this.primitiveParameter = [];
346             const formArr: AbstractControl[] = this.getControls();
347             formArr.forEach((formGp: FormGroup): void => {
348                 formGp.controls.primitive_params_name.setValidators([]);
349                 formGp.controls.primitive_params_name.updateValueAndValidity();
350                 formGp.controls.primitive_params_value.setValidators([]);
351                 formGp.controls.primitive_params_value.updateValueAndValidity();
352             });
353         }
354     }
355     /** Get primivitive actions from vnfd data */
356     private getVnfdInfo(vnfdRef: string, getType?: string): void {
357         this.primitiveList = [];
358         this.primitiveParameter = [];
359         this.getFormControl('primitive').setValue(null);
360         const apiUrl: string = environment.VNFPACKAGES_URL + '?id=' + vnfdRef;
361         this.isLoadingResults = true;
362         this.restService.getResource(apiUrl).subscribe((vnfdInfo: VNFD[]): void => {
363             const vnfInstances: VNFD = vnfdInfo[0];
364             if (!isNullOrUndefined(vnfInstances.df)) {
365                 this.getFormControl('vdu_id').setValidators([]);
366                 this.getFormControl('kdu_name').setValidators([]);
367                 vnfInstances.df.forEach((df: DF): void => {
368                     if (df['lcm-operations-configuration'] !== undefined) {
369                         if (df['lcm-operations-configuration']['operate-vnf-op-config'] !== undefined) {
370                             const day12Operation: VDUCONFIG[] = df['lcm-operations-configuration']['operate-vnf-op-config']['day1-2'];
371                             if (day12Operation !== undefined) {
372                                 const vnfprimitiveList: VNFCONFIG = day12Operation
373                                     .filter((itemData: VNFCONFIG): boolean => itemData.id === vnfInstances.id)[0];
374                                 if (vnfprimitiveList !== undefined) {
375                                     this.primitiveList = vnfprimitiveList['config-primitive'];
376                                 }
377                                 /** VDU Primitive */
378                                 if (getType === 'VDU_Primitive') {
379                                     this.kduList = [];
380                                     this.vduList = [];
381                                     this.primitiveList = [];
382                                     df['vdu-profile'].forEach((vduProfile: VDUPROFILE): void => {
383                                         day12Operation.forEach((element: VDUCONFIG): void => {
384                                             if (element.id === vduProfile.id) {
385                                                 const vduDataObj: VDUPROFILE = this.generateVDUData(element);
386                                                 this.vduList.push(vduDataObj);
387                                             }
388                                         });
389                                     });
390                                 }
391                                 /** KDU Primitive */
392                                 if (getType === 'KDU_Primitive') {
393                                     this.kduList = [];
394                                     this.vduList = [];
395                                     this.primitiveList = [];
396                                     if (!isNullOrUndefined(vnfInstances.kdu)) {
397                                         vnfInstances.kdu.forEach((kduData: KDUPRIMITIVELEVEL): void => {
398                                             day12Operation.forEach((element: VDUCONFIG): void => {
399                                                 if (element.id === kduData.name) {
400                                                     const kduDataObj: KDUPRIMITIVELEVEL = this.generateKDUData(kduData, element);
401                                                     this.kduList.push(kduDataObj);
402                                                 }
403                                             });
404                                         });
405                                     }
406                                 }
407                             }
408                         }
409                     }
410                 });
411             }
412             this.isLoadingResults = false;
413         }, (error: ERRORDATA): void => {
414             this.isLoadingResults = false;
415             this.restService.handleError(error, 'get');
416         });
417     }
418     /** Get primivitive actions from NSD data */
419     private getNSInfo(nsdRef: string): void {
420         this.primitiveList = [];
421         this.primitiveParameter = [];
422         this.getFormControl('primitive').setValue(null);
423         const apiUrl: string = environment.NSDESCRIPTORS_URL + '?id=' + nsdRef;
424         this.isLoadingResults = true;
425         this.restService.getResource(apiUrl)
426             .subscribe((nsdInfo: {}): void => {
427                 if (!isNullOrUndefined(nsdInfo[0]['ns-configuration'])) {
428                     this.primitiveList = !isNullOrUndefined(nsdInfo[0]['ns-configuration']['config-primitive']) ?
429                         nsdInfo[0]['ns-configuration']['config-primitive'] : [];
430                 } else {
431                     this.primitiveList = [];
432                 }
433                 this.isLoadingResults = false;
434             }, (error: ERRORDATA): void => {
435                 this.isLoadingResults = false;
436                 this.restService.handleError(error, 'get');
437             });
438     }
439     /** Used to get the AbstractControl of controlName passed @private */
440     private getFormControl(controlName: string): AbstractControl {
441         // eslint-disable-next-line security/detect-object-injection
442         return this.primitiveForm.controls[controlName];
443     }
444 }