097e450daa3ef75113d747725969d3d673897eae
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / ei-coordinator / jobs-list / jobs-list.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20 import { Component, OnInit, ViewChild } from "@angular/core";
21 import { FormControl, FormGroup } from "@angular/forms";
22 import { MatPaginator } from "@angular/material/paginator";
23 import { Sort } from "@angular/material/sort";
24 import { MatTableDataSource } from "@angular/material/table";
25 import { EMPTY, forkJoin, of, pipe, Subscription, concat, Observable } from "rxjs";
26 import { BehaviorSubject } from "rxjs/BehaviorSubject";
27 import { mergeMap, finalize, map, tap, concatMap, delay, skip, catchError } from "rxjs/operators";
28 import { ConsumerService } from "@services/ei/consumer.service";
29 import { UiService } from "@services/ui/ui.service";
30 import { OperationalState } from '@app/interfaces/consumer.types';
31
32 export interface Job {
33   jobId: string;
34   typeId: string;
35   targetUri: string;
36   owner: string;
37   prodIds: string[];
38   status: OperationalState;
39 }
40
41 @Component({
42   selector: "nrcp-jobs-list",
43   templateUrl: "./jobs-list.component.html",
44   styleUrls: ["./jobs-list.component.scss"],
45 })
46 export class JobsListComponent implements OnInit {
47   @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
48   jobsDataSource: MatTableDataSource<Job>;
49   jobForm: FormGroup;
50   darkMode: boolean;
51
52   private jobsSubject$ = new BehaviorSubject<Job[]>([]);
53   private refresh$ = new BehaviorSubject("");
54   private loadingSubject$ = new BehaviorSubject<boolean>(false);
55   private polling$ = new BehaviorSubject(0);
56   public loading$ = this.loadingSubject$.asObservable();
57   subscription: Subscription;
58   checked: boolean = false;
59   firstTime: boolean = true;
60   jobList: Job[] = [];
61
62   constructor(private consumerService: ConsumerService, private ui: UiService) {
63     this.jobForm = new FormGroup({
64       jobId: new FormControl(""),
65       typeId: new FormControl(""),
66       owner: new FormControl(""),
67       targetUri: new FormControl(""),
68       prodIds: new FormControl(""),
69       status: new FormControl("")
70     });
71   }
72
73   ngOnInit(): void {
74     this.subscription = this.dataSubscription();
75
76     this.jobsSubject$.subscribe((data) => {
77       this.jobsDataSource = new MatTableDataSource<Job>(data);
78       this.jobsDataSource.paginator = this.paginator;
79
80       this.jobsDataSource.filterPredicate = ((data: Job, filter) => {
81         let searchTerms = JSON.parse(filter);
82         return (
83           this.isDataIncluding(data.targetUri, searchTerms.targetUri) &&
84           this.isDataIncluding(data.jobId, searchTerms.jobId) &&
85           this.isDataIncluding(data.owner, searchTerms.owner) &&
86           this.isDataIncluding(data.typeId, searchTerms.typeId) &&
87           this.isArrayIncluding(data.prodIds, searchTerms.prodIds) &&
88           this.isDataIncluding(data.status, searchTerms.status)
89         );
90       }) as (data: Job, filter: any) => boolean;
91     });
92
93     this.jobForm.valueChanges.subscribe((value) => {
94       this.jobsDataSource.filter = JSON.stringify(value);
95     });
96
97     this.ui.darkModeState.subscribe((isDark) => {
98       this.darkMode = isDark;
99     });
100   }
101
102   dataSubscription(): Subscription {
103     const jobsInfo$ = this.consumerService.getJobIds().pipe(
104       tap((_) => {
105         this.jobList = [] as Job[];
106       }),
107       mergeMap((jobIds) =>
108         forkJoin(jobIds.map((jobId) => {
109           return forkJoin([
110             of(jobId).pipe(
111               catchError(err => {
112                 return of([-1]);
113               })
114             ),
115             this.consumerService.getJobInfo(jobId).pipe(
116               catchError(err => {
117                 return of([-1]);
118               })),
119             this.consumerService.getConsumerStatus(jobId).pipe(
120               catchError(err => {
121                 return of([-1]);
122               })),
123           ])
124         }))
125       ),
126       finalize(() => {
127         this.loadingSubject$.next(false);
128         this.jobsSubject$.next(this.jobList);
129       })
130     );
131
132     const whenToRefresh$ = of('').pipe(
133       delay(10000),
134       tap((_) => this.refresh$.next('')),
135       skip(1),
136     );
137
138     const poll$ = concat(jobsInfo$, whenToRefresh$);
139
140     const refreshedJobs$ = this.refresh$.pipe(
141       tap((_) => {
142         this.loadingSubject$.next(true);
143       }),
144       concatMap((_) => this.checked ? poll$ : jobsInfo$),
145       map((response) => this.extractJobs(response))
146     );
147
148     return this.polling$
149       .pipe(
150         concatMap((value) => {
151           let pollCondition = value == 0 || this.checked;
152           return pollCondition ? refreshedJobs$ : EMPTY;
153         })
154       )
155       .subscribe();
156   }
157
158   ngOnDestroy() {
159     this.subscription.unsubscribe();
160   }
161
162   clearFilter() {
163     this.jobForm.get("jobId").setValue("");
164     this.jobForm.get("typeId").setValue("");
165     this.jobForm.get("owner").setValue("");
166     this.jobForm.get("targetUri").setValue("");
167     this.jobForm.get("prodIds").setValue("");
168     this.jobForm.get("status").setValue("");
169   }
170
171   sortJobs(sort: Sort) {
172     const data = this.jobsDataSource.data;
173     data.sort((a: Job, b: Job) => {
174       const isAsc = sort.direction === "asc";
175       switch (sort.active) {
176         case "jobId":
177           return this.compare(a.jobId, b.jobId, isAsc);
178         case "typeId":
179           return this.compare(a.typeId, b.typeId, isAsc);
180         case "owner":
181           return this.compare(a.owner, b.owner, isAsc);
182         case "targetUri":
183           return this.compare(a.targetUri, b.targetUri, isAsc);
184         case "prodIds":
185           return this.compare(a.prodIds, b.prodIds, isAsc);
186         case "status":
187           return this.compare(a.status, b.status, isAsc);
188         default:
189           return 0;
190       }
191     });
192     this.jobsDataSource.data = data;
193   }
194
195   stopPolling(checked) {
196     this.checked = checked;
197     this.polling$.next(this.jobs().length);
198     if (this.checked) {
199       this.refreshDataClick();
200     }
201   }
202
203   compare(a: any, b: any, isAsc: boolean) {
204     return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
205   }
206
207   stopSort(event: any) {
208     event.stopPropagation();
209   }
210
211   isDataIncluding(data: string, filter: string): boolean {
212     const transformedFilter = filter.trim().toLowerCase();
213     return data.toLowerCase().includes(transformedFilter);
214   }
215
216   isArrayIncluding(data: string[], filter: string): boolean {
217     if (!data)
218       return true;
219     for (let i = 0; i < data.length; i++) {
220       return this.isDataIncluding(data[i], filter);
221     }
222   }
223
224   getJobTypeId(job: Job): string {
225     if (job.typeId) {
226       return job.typeId;
227     }
228     return "< No type >";
229   }
230
231   getJobOwner(job: Job): string {
232     if (job.owner) {
233       return job.owner;
234     }
235     return "< No owner >";
236   }
237
238   public jobs(): Job[] {
239     return this.jobsSubject$.value;
240   }
241
242   private extractJobs(res: any) {
243     this.clearFilter();
244     res.forEach(element => {
245       if (element[0] != -1) {
246         if (element[1] != -1 && element[2] != -1) {
247           let jobObj = <Job>{};
248           jobObj.jobId = element[0];
249           jobObj.owner = element[1].job_owner;
250           jobObj.targetUri = element[1].job_result_uri;
251           jobObj.typeId = element[1].info_type_id;
252           jobObj.prodIds = (element[2].producers) ? element[2].producers : ["No Producers"];
253           jobObj.status = element[2].info_job_status;
254           this.jobList = this.jobList.concat(jobObj);
255         } else {
256           let jobObj = <Job>{};
257           jobObj.jobId = element[0];
258           if (element[1] == -1) {
259             jobObj.owner = "--Missing information--";
260             jobObj.targetUri = "--Missing information--";
261             jobObj.typeId = "--Missing information--";
262           }
263           if (element[2] == -1) {
264             jobObj.prodIds = "--Missing information--" as unknown as [];
265             jobObj.status = "--Missing information--" as OperationalState;
266           }
267           this.jobList = this.jobList.concat(jobObj);
268         }
269       }
270     });
271
272     if (this.firstTime && this.jobList.length > 0) {
273       this.polling$.next(this.jobList.length);
274       this.firstTime = false;
275     }
276     return this.jobList;
277   }
278
279   refreshDataClick() {
280     this.refresh$.next("");
281   }
282
283   hasJobs(): boolean {
284     return this.jobs().length > 0;
285   }
286
287 }