Angular upgrade
[osm/NG-UI.git] / src / app / utilities / start-stop-rebuild / StartStopRebuildComponent.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: SANDHYA JS (sandhya.j@tataelxsi.co.in)
17 */
18 /**
19  * @file StartStopRebuild Component
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Router } from '@angular/router';
25 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
26 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, URLPARAMS } from 'CommonModel';
27 import { environment } from 'environment';
28 import { StartStopRebuild } from 'NSInstanceModel';
29 import { RestService } from 'RestService';
30 import { SharedService, isNullOrUndefined } from 'SharedService';
31 import { DF, VNFD } from 'VNFDModel';
32 import { InstanceData, VDUR, VNFInstanceDetails } from 'VNFInstanceModel';
33
34 /**
35  * Creating component
36  * @Component takes StartStopRebuildComponent.html as template url
37  */
38 @Component({
39     selector: 'app-start-stop-rebuild',
40     templateUrl: './StartStopRebuildComponent.html',
41     styleUrls: ['./StartStopRebuildComponent.scss']
42 })
43 export class StartStopRebuildComponent implements OnInit {
44     /** To inject services @public */
45     public injector: Injector;
46     /** Instance for active modal service @public */
47     public activeModal: NgbActiveModal;
48     /** Check the loading results @public */
49     public isLoadingResults: Boolean = false;
50     /** Give the message for the loading @public */
51     public message: string = 'PLEASEWAIT';
52     /** FormGroup instance added to the form @ html @public */
53     public startForm: FormGroup;
54     /** Items for the memberVNFIndex @public */
55     public memberTypes: {}[];
56     /** Contains MemberVNFIndex values @public */
57     public memberVnfIndex: {}[] = [];
58     /** Contains vnfInstanceId of the selected MemberVnfIndex  @public */
59     public instanceId: string;
60     /** Items for vduId & countIndex @public */
61     public vdu: {}[];
62     /** Selected VNFInstanceId @public */
63     public selectedvnfId: string = '';
64     /** Check day1-2 operation  @public */
65     public 'day1-2': boolean;
66     /** Array holds VNFR Data filtered with nsr ID @public */
67     public nsIdFilteredData: {}[] = [];
68     /** Form valid on submit trigger @public */
69     public submitted: boolean = false;
70     /** Contains vduId @public */
71     public vduId: {};
72     /** Items for countIndex @public */
73     public countIndex: {}[];
74     /** Input contains Modal dialog component Instance @public */
75     @Input() public instanceType: string;
76     /** Input contains Modal dialog component Instance @public */
77     @Input() public instanceTitle: string;
78     /** Input contains component objects @private */
79     @Input() private params: URLPARAMS;
80     /** FormBuilder instance added to the formBuilder @private */
81     private formBuilder: FormBuilder;
82     /** Instance of the rest service @private */
83     private restService: RestService;
84     /** Controls the header form @private */
85     private headers: HttpHeaders;
86     /** Contains all methods related to shared @private */
87     private sharedService: SharedService;
88     /** Holds the instance of AuthService class of type AuthService @private */
89     private router: Router;
90     constructor(injector: Injector) {
91         this.injector = injector;
92         this.restService = this.injector.get(RestService);
93         this.activeModal = this.injector.get(NgbActiveModal);
94         this.formBuilder = this.injector.get(FormBuilder);
95         this.sharedService = this.injector.get(SharedService);
96         this.router = this.injector.get(Router);
97     }
98     /** convenience getter for easy access to form fields */
99     get f(): FormGroup['controls'] { return this.startForm.controls; }
100     /**
101      * Lifecyle Hooks the trigger before component is instantiate
102      */
103     public ngOnInit(): void {
104         this.initializeForm();
105         this.getMemberVnfIndex();
106         this.headers = new HttpHeaders({
107             'Content-Type': 'application/json',
108             Accept: 'application/json',
109             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
110         });
111     }
112     /** Initialize start, stop or rebuild Forms @public */
113     public initializeForm(): void {
114         this.startForm = this.formBuilder.group({
115             memberVnfIndex: [null, [Validators.required]],
116             vduId: [null, [Validators.required]],
117             countIndex: [null, [Validators.required]]
118         });
119     }
120
121     /** Getting MemberVnfIndex using VNFInstances API @public */
122     public getMemberVnfIndex(): void {
123         this.isLoadingResults = true;
124         const vnfInstanceData: {}[] = [];
125         this.restService.getResource(environment.VNFINSTANCES_URL).subscribe((vnfInstancesData: VNFInstanceDetails[]): void => {
126             vnfInstancesData.forEach((vnfData: VNFInstanceDetails): void => {
127                 const vnfdRef: string = 'vnfd-ref';
128                 const memberIndex: string = 'member-vnf-index-ref';
129                 const nsrId: string = 'nsr-id-ref';
130                 const vnfId: string = 'vnfd-id';
131                 const vnfDataObj: {} =
132                 {
133                     // eslint-disable-next-line security/detect-object-injection
134                     VNFD: vnfData[vnfdRef],
135                     VNFInstanceId: vnfData._id,
136                     // eslint-disable-next-line security/detect-object-injection
137                     MemberIndex: vnfData[memberIndex],
138                     // eslint-disable-next-line security/detect-object-injection
139                     NS: vnfData[nsrId],
140                     // eslint-disable-next-line security/detect-object-injection
141                     VNFID: vnfData[vnfId]
142                 };
143                 vnfInstanceData.push(vnfDataObj);
144             });
145             const nsId: string = 'NS';
146             // eslint-disable-next-line security/detect-object-injection
147             this.nsIdFilteredData = vnfInstanceData.filter((vnfdData: {}[]): boolean => vnfdData[nsId] === this.params.id);
148             this.nsIdFilteredData.forEach((resVNF: InstanceData): void => {
149                 const assignMemberIndex: {} = {
150                     id: resVNF.MemberIndex,
151                     vnfinstanceId: resVNF.VNFInstanceId
152                 };
153                 this.memberVnfIndex.push(assignMemberIndex);
154             });
155             this.memberTypes = this.memberVnfIndex;
156             this.isLoadingResults = false;
157         }, (error: ERRORDATA): void => {
158             this.restService.handleError(error, 'get');
159             this.isLoadingResults = false;
160         });
161     }
162
163     /** Getting vdu-id & count-index from VNFInstance API */
164     public getVdu(id: string): void {
165         const vnfInstanceData: {}[] = [];
166         this.getFormControl('vduId').setValue(null);
167         this.getFormControl('countIndex').setValue(null);
168         if (!isNullOrUndefined(id)) {
169             this.restService.getResource(environment.VNFINSTANCES_URL + '/' + id).
170                 subscribe((vnfInstanceDetail: VNFInstanceDetails[]): void => {
171                     this.instanceId = id;
172                     this.selectedvnfId = vnfInstanceDetail['vnfd-ref'];
173                     const VDU: string = 'vdur';
174                     // eslint-disable-next-line security/detect-object-injection
175                     if (vnfInstanceDetail[VDU] !== undefined) {
176                         // eslint-disable-next-line security/detect-object-injection
177                         vnfInstanceDetail[VDU].forEach((vdu: VDUR): void => {
178                             const vnfInstanceDataObj: {} =
179                             {
180                                 'count-index': vdu['count-index'],
181                                 VDU: vdu['vdu-id-ref']
182                             };
183                             vnfInstanceData.push(vnfInstanceDataObj);
184                         });
185                         this.vdu = vnfInstanceData;
186                         const vduName: string = 'VDU';
187                         this.vduId = this.vdu.filter((vdu: {}, index: number, self: {}[]): {} =>
188                             index === self.findIndex((t: {}): {} => (
189                                 // eslint-disable-next-line security/detect-object-injection
190                                 t[vduName] === vdu[vduName]
191                             ))
192                         );
193                     }
194                     this.checkDay12Operation(this.selectedvnfId);
195                 }, (error: ERRORDATA): void => {
196                     this.restService.handleError(error, 'get');
197                     this.isLoadingResults = false;
198                 });
199         }
200     }
201
202     /** Getting count-index by filtering id */
203     public getCountIndex(id: string): void {
204         const VDU: string = 'VDU';
205         // eslint-disable-next-line security/detect-object-injection
206         this.countIndex = this.vdu.filter((vnfdData: {}[]): boolean => vnfdData[VDU] === id);
207     }
208
209     /** To check primitve actions from VNFR  */
210     public checkDay12Operation(id: string): void {
211         const apiUrl: string = environment.VNFPACKAGES_URL + '?id=' + id;
212         this.restService.getResource(apiUrl).subscribe((vnfdInfo: VNFD[]): void => {
213             const vnfInstances: VNFD = vnfdInfo[0];
214             if (!isNullOrUndefined(vnfInstances.df)) {
215                 vnfInstances.df.forEach((df: DF): void => {
216                     if (df['lcm-operations-configuration'] !== undefined) {
217                         if (df['lcm-operations-configuration']['operate-vnf-op-config']['day1-2'] !== undefined) {
218                             this['day1-2'] = true;
219                         }
220                     } else {
221                         this['day1-2'] = false;
222                     }
223                 });
224             }
225         }, (error: ERRORDATA): void => {
226             this.isLoadingResults = false;
227             this.restService.handleError(error, 'get');
228         });
229     }
230     /** Check Instance type is start or stop or rebuild and proceed action */
231     public instanceCheck(instanceType: string): void {
232         this.submitted = true;
233         this.sharedService.cleanForm(this.startForm);
234         if (this.startForm.invalid) { return; } // Proceed, onces form is valid
235         if (instanceType === 'start') {
236             const startPayload: StartStopRebuild = {
237                 updateType: 'OPERATE_VNF',
238                 operateVnfData: {
239                     vnfInstanceId: this.instanceId,
240                     changeStateTo: 'start',
241                     additionalParam: {
242                         'run-day1': false,
243                         vdu_id: this.startForm.value.vduId,
244                         'count-index': this.startForm.value.countIndex
245                     }
246                 }
247             };
248             this.startInitialization(startPayload);
249         } else if (instanceType === 'stop') {
250             const stopPayload: StartStopRebuild = {
251                 updateType: 'OPERATE_VNF',
252                 operateVnfData: {
253                     vnfInstanceId: this.instanceId,
254                     changeStateTo: 'stop',
255                     additionalParam: {
256                         'run-day1': false,
257                         vdu_id: this.startForm.value.vduId,
258                         'count-index': this.startForm.value.countIndex
259                     }
260                 }
261             };
262             this.startInitialization(stopPayload);
263         } else {
264             const rebuildPayload: StartStopRebuild = {
265                 updateType: 'OPERATE_VNF',
266                 operateVnfData: {
267                     vnfInstanceId: this.instanceId,
268                     changeStateTo: 'rebuild',
269                     additionalParam: {
270                         'run-day1': (this['day1-2'] === true) ? true : false,
271                         vdu_id: this.startForm.value.vduId,
272                         'count-index': this.startForm.value.countIndex
273                     }
274                 }
275             };
276             this.startInitialization(rebuildPayload);
277         }
278     }
279
280     /** Initialize the start, stop or rebuild operation @public */
281     public startInitialization(startPayload: object): void {
282         this.isLoadingResults = true;
283         const apiURLHeader: APIURLHEADER = {
284             url: environment.NSDINSTANCES_URL + '/' + this.params.id + '/update',
285             httpOptions: { headers: this.headers }
286         };
287         const modalData: MODALCLOSERESPONSEDATA = {
288             message: 'Done'
289         };
290         this.restService.postResource(apiURLHeader, startPayload).subscribe((result: {}): void => {
291             this.activeModal.close(modalData);
292             this.router.navigate(['/instances/ns/history-operations/' + this.params.id]).catch((): void => {
293                 // Catch Navigation Error
294             });
295         }, (error: ERRORDATA): void => {
296             this.restService.handleError(error, 'post');
297             this.isLoadingResults = false;
298         });
299     }
300
301     /** Used to get the AbstractControl of controlName passed @private */
302     private getFormControl(controlName: string): AbstractControl {
303         // eslint-disable-next-line security/detect-object-injection
304         return this.startForm.controls[controlName];
305     }
306 }