NG-UI Bug 1136 - Unable to execute NS level primitive
[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, URLPARAMS } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { NSData, VDUPRIMITIVELEVEL } from 'NSDModel';
30 import { NSPrimitiveParams } from 'NSInstanceModel';
31 import { RestService } from 'RestService';
32 import { SharedService } from 'SharedService';
33 import { isNullOrUndefined } from 'util';
34
35 /**
36  * Creating component
37  * @Component takes NSPrimitiveComponent.html as template url
38  */
39 @Component({
40     templateUrl: './NSPrimitiveComponent.html',
41     styleUrls: ['./NSPrimitiveComponent.scss']
42 })
43 /** Exporting a class @exports NSPrimitiveComponent */
44 export class NSPrimitiveComponent implements OnInit {
45     /** Form valid on submit trigger @public */
46     public submitted: boolean = false;
47
48     /** To inject services @public */
49     public injector: Injector;
50
51     /** Instance for active modal service @public */
52     public activeModal: NgbActiveModal;
53
54     /** FormGroup instance added to the form @ html @public */
55     public primitiveForm: FormGroup;
56
57     /** Primitive params array @public */
58     public primitiveParams: FormArray;
59
60     /** Variable set for twoway binding @public */
61     public nsdId: string;
62
63     /** Check the loading results @public */
64     public isLoadingResults: boolean = false;
65
66     /** Give the message for the loading @public */
67     public message: string = 'PLEASEWAIT';
68
69     /** Contains list of primitive parameter @public */
70     public primitiveParameter: {}[] = [];
71
72     /** Input contains component objects @public */
73     @Input() public params: URLPARAMS;
74
75     /** Contains list of primitive actions @public */
76     public primitiveList: {}[];
77
78     /** Contains objects that is used to hold types of primitive @public */
79     public primitiveTypeList: {}[] = [];
80
81     /** Model value used to hold selected primitive type @public */
82     public primitiveType: string;
83
84     /** Contains list of VDU primitive lists @public */
85     public vduList: {}[];
86
87     /** FormBuilder instance added to the formBuilder @private */
88     private formBuilder: FormBuilder;
89
90     /** Utilizes rest service for any CRUD operations @private */
91     private restService: RestService;
92
93     /** packages data service collections @private */
94     private dataService: DataService;
95
96     /** Contains tranlsate instance @private */
97     private translateService: TranslateService;
98
99     /** Notifier service to popup notification @private */
100     private notifierService: NotifierService;
101
102     /** Contains all methods related to shared @private */
103     private sharedService: SharedService;
104
105     /** Contains objects that is used to convert key/value pair @private */
106     private objectPrimitiveParams: {} = {};
107
108     constructor(injector: Injector) {
109         this.injector = injector;
110         this.restService = this.injector.get(RestService);
111         this.dataService = this.injector.get(DataService);
112         this.translateService = this.injector.get(TranslateService);
113         this.notifierService = this.injector.get(NotifierService);
114         this.sharedService = this.injector.get(SharedService);
115         this.activeModal = this.injector.get(NgbActiveModal);
116         this.formBuilder = this.injector.get(FormBuilder);
117         this.primitiveTypeList = [
118             {
119                 title: this.translateService.instant('NSPRIMITIVE'),
120                 value: 'NS_Primitive'
121             },
122             {
123                 title: this.translateService.instant('VNFPRIMITIVE'),
124                 value: 'VNF_Primitive'
125             },
126             {
127                 title: this.translateService.instant('VDUPRIMITIVE'),
128                 value: 'VDU_Primitive'
129             }
130         ];
131     }
132
133     /**
134      * Lifecyle Hooks the trigger before component is instantiate
135      */
136     public ngOnInit(): void {
137         /** Setting up initial value for NSD */
138         this.dataService.currentMessage.subscribe((event: NSData) => {
139             if (event.identifier !== undefined || event.identifier !== '' || event.identifier !== null) {
140                 this.nsdId = event.identifier;
141             }
142         });
143         this.initializeForm();
144     }
145
146     /** convenience getter for easy access to form fields */
147     get f(): FormGroup['controls'] { return this.primitiveForm.controls; }
148
149     /** initialize Forms @public */
150     public initializeForm(): void {
151         this.primitiveForm = this.formBuilder.group({
152             primitive: [null, [Validators.required]],
153             vnf_member_index: [null, [Validators.required]],
154             vdu_id: [null, [Validators.required]],
155             primitive_params: this.formBuilder.array([this.primitiveParamsBuilder()])
156         });
157     }
158
159     /** Generate primitive params @public */
160     public primitiveParamsBuilder(): FormGroup {
161         return this.formBuilder.group({
162             primitive_params_name: [null, [Validators.required]],
163             primitive_params_value: ['', [Validators.required]]
164         });
165     }
166
167     /** Handle FormArray Controls @public */
168     public getControls(): AbstractControl[] {
169         return (this.getFormControl('primitive_params') as FormArray).controls;
170     }
171
172     /** Push all primitive params on user's action @public */
173     public createPrimitiveParams(): void {
174         this.primitiveParams = this.getFormControl('primitive_params') as FormArray;
175         this.primitiveParams.push(this.primitiveParamsBuilder());
176     }
177
178     /** Remove primitive params on user's action @public */
179     public removePrimitiveParams(index: number): void {
180         this.primitiveParams.removeAt(index);
181     }
182
183     /** Execute NS Primitive @public */
184     public execNSPrimitive(): void {
185         this.submitted = true;
186         this.objectPrimitiveParams = {};
187         this.sharedService.cleanForm(this.primitiveForm);
188         if (this.primitiveForm.invalid) { return; } // Proceed, onces form is valid
189         this.primitiveForm.value.primitive_params.forEach((params: NSPrimitiveParams) => {
190             if (params.primitive_params_name !== null && params.primitive_params_value !== '') {
191                 this.objectPrimitiveParams[params.primitive_params_name] = params.primitive_params_value;
192             }
193         });
194         //Prepare primitive params
195         const primitiveParamsPayLoads: {} = {
196             primitive: this.primitiveForm.value.primitive,
197             primitive_params: this.objectPrimitiveParams
198         };
199         if (this.primitiveType === 'VNF_Primitive') {
200             // tslint:disable-next-line: no-string-literal
201             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
202         }
203         if (this.primitiveType === 'VDU_Primitive') {
204             // tslint:disable-next-line: no-string-literal
205             primitiveParamsPayLoads['vnf_member_index'] = this.primitiveForm.value.vnf_member_index;
206             // tslint:disable-next-line: no-string-literal
207             primitiveParamsPayLoads['vdu_id'] = this.primitiveForm.value.vdu_id;
208         }
209         const apiURLHeader: APIURLHEADER = {
210             url: environment.NSDINSTANCES_URL + '/' + this.nsdId + '/action'
211         };
212         this.isLoadingResults = true;
213         this.restService.postResource(apiURLHeader, primitiveParamsPayLoads).subscribe((result: {}) => {
214             this.activeModal.dismiss();
215             this.notifierService.notify('success', this.translateService.instant('PAGE.NSPRIMITIVE.EXECUTEDSUCCESSFULLY'));
216             this.isLoadingResults = false;
217         }, (error: ERRORDATA) => {
218             this.isLoadingResults = false;
219             this.restService.handleError(error, 'post');
220         });
221     }
222     /** Primitive type change event @public */
223     public primitiveTypeChange(data: { value: string }): void {
224         this.primitiveList = [];
225         this.primitiveParameter = [];
226         this.initializeForm();
227         if (data.value === 'NS_Primitive') {
228             this.getNSInfo(this.params.name);
229             this.getFormControl('vnf_member_index').setValidators([]);
230             this.getFormControl('vnf_member_index').updateValueAndValidity();
231             this.getFormControl('vdu_id').setValidators([]);
232             this.getFormControl('vdu_id').updateValueAndValidity();
233         }
234     }
235     /** Member index change event */
236     public indexChange(data: {}, getType?: string): void {
237         this.getFormControl('vdu_id').setValue(null);
238         if (data) {
239             this.getVnfdInfo(data['vnfd-id-ref'], getType);
240         } else {
241             this.primitiveList = [];
242             this.getFormControl('primitive').setValue(null);
243             this.primitiveParameter = [];
244         }
245     }
246     /** Get VDU Primitive from selected VDU id/name change event */
247     public getVDUPrimitive(data: {}): void {
248         this.primitiveList = data['vdu-configuration']['config-primitive'];
249     }
250     /** Primivtive change event */
251     public primitiveChange(data: { parameter: {}[] }): void {
252         this.primitiveParameter = [];
253         const formArr: FormArray = this.getFormControl('primitive_params') as FormArray;
254         formArr.controls = [];
255         this.createPrimitiveParams();
256         if (data) {
257             this.updatePrimitive(data);
258         }
259     }
260     /** Generate vdu section @public */
261     public generateVDUData(vduData: VDUPRIMITIVELEVEL): VDUPRIMITIVELEVEL {
262         return {
263             id: vduData.id,
264             name: vduData.name,
265             'vdu-configuration': vduData['vdu-configuration']
266         };
267     }
268     /** Update primitive value based on parameter */
269     private updatePrimitive(primitive: { parameter: {}[] }): void {
270         if (primitive.parameter) {
271             this.primitiveParameter = primitive.parameter;
272         } else {
273             this.primitiveParameter = [];
274             const formArr: AbstractControl[] = this.getControls();
275             formArr.forEach((formGp: FormGroup) => {
276                 formGp.controls.primitive_params_name.setValidators([]);
277                 formGp.controls.primitive_params_name.updateValueAndValidity();
278                 formGp.controls.primitive_params_value.setValidators([]);
279                 formGp.controls.primitive_params_value.updateValueAndValidity();
280             });
281         }
282     }
283     /** Get primivitive actions from vnfd data */
284     private getVnfdInfo(vnfdRef: string, getType?: string): void {
285         this.primitiveList = [];
286         this.primitiveParameter = [];
287         this.getFormControl('primitive').setValue(null);
288         const apiUrl: string = environment.VNFPACKAGES_URL + '?short-name=' + vnfdRef;
289         this.isLoadingResults = true;
290         this.restService.getResource(apiUrl)
291             .subscribe((vnfdInfo: {}) => {
292                 if (vnfdInfo[0]['vnf-configuration']) {
293                     this.getFormControl('vdu_id').setValidators([]);
294                     this.primitiveList = vnfdInfo[0]['vnf-configuration']['config-primitive'];
295                 }
296                 if (getType === 'VDU_Primitive') {
297                     this.vduList = [];
298                     vnfdInfo[0].vdu.forEach((vduData: VDUPRIMITIVELEVEL) => {
299                         if (vduData['vdu-configuration']) {
300                             const vduDataObj: VDUPRIMITIVELEVEL = this.generateVDUData(vduData);
301                             this.vduList.push(vduDataObj);
302                         }
303                     });
304                 }
305                 this.isLoadingResults = false;
306             }, (error: ERRORDATA) => {
307                 this.isLoadingResults = false;
308                 this.restService.handleError(error, 'get');
309             });
310     }
311     /** Get primivitive actions from NSD data */
312     private getNSInfo(nsdRef: string): void {
313         this.primitiveList = [];
314         this.primitiveParameter = [];
315         this.getFormControl('primitive').setValue(null);
316         const apiUrl: string = environment.NSDESCRIPTORS_URL + '?short-name=' + nsdRef;
317         this.isLoadingResults = true;
318         this.restService.getResource(apiUrl)
319             .subscribe((nsdInfo: {}) => {
320                 this.primitiveList = !isNullOrUndefined(nsdInfo[0]['ns-configuration']['config-primitive']) ?
321                 nsdInfo[0]['ns-configuration']['config-primitive'] : [];
322                 this.isLoadingResults = false;
323             }, (error: ERRORDATA) => {
324                 this.isLoadingResults = false;
325                 this.restService.handleError(error, 'get');
326             });
327     }
328     /** Used to get the AbstractControl of controlName passed @private */
329     private getFormControl(controlName: string): AbstractControl {
330         return this.primitiveForm.controls[controlName];
331     }
332 }