Fix EI jobs count stopping too early
[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 } from "rxjs";
26 import { BehaviorSubject } from "rxjs/BehaviorSubject";
27 import { mergeMap, finalize, map, tap, concatMap, delay, skip } from "rxjs/operators";
28 import { ConsumerService } from "@services/ei/consumer.service";
29 import { UiService } from "@services/ui/ui.service";
30
31 export interface Job {
32   jobId: string;
33   typeId: string;
34   targetUri: string;
35   owner: string;
36   prodIds: string[];
37 }
38
39 @Component({
40   selector: "nrcp-jobs-list",
41   templateUrl: "./jobs-list.component.html",
42   styleUrls: ["./jobs-list.component.scss"],
43 })
44 export class JobsListComponent implements OnInit {
45   @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
46   jobsDataSource: MatTableDataSource<Job>;
47   jobForm: FormGroup;
48   darkMode: boolean;
49
50   private jobsSubject$ = new BehaviorSubject<Job[]>([]);
51   private refresh$ = new BehaviorSubject("");
52   private loadingSubject$ = new BehaviorSubject<boolean>(false);
53   private polling$ = new BehaviorSubject(0);
54   public loading$ = this.loadingSubject$.asObservable();
55   subscription: Subscription;
56   checked: boolean = false;
57   firstTime: boolean = true;
58
59   constructor(private consumerService: ConsumerService, private ui: UiService) {
60     this.jobForm = new FormGroup({
61       jobId: new FormControl(""),
62       typeId: new FormControl(""),
63       owner: new FormControl(""),
64       targetUri: new FormControl(""),
65       prodIds: new FormControl(""),
66     });
67   }
68
69   ngOnInit(): void {
70     this.subscription = this.dataSubscription();
71
72     this.jobsSubject$.subscribe((data) => {
73       this.jobsDataSource = new MatTableDataSource<Job>(data);
74       this.jobsDataSource.paginator = this.paginator;
75
76       this.jobsDataSource.filterPredicate = ((data: Job, filter) => {
77         let searchTerms = JSON.parse(filter);
78         return (
79           this.isDataIncluding(data.targetUri, searchTerms.targetUri) &&
80           this.isDataIncluding(data.jobId, searchTerms.jobId) &&
81           this.isDataIncluding(data.owner, searchTerms.owner) &&
82           this.isDataIncluding(data.typeId, searchTerms.typeId) &&
83           this.isArrayIncluding(data.prodIds, searchTerms.prodIds)
84         );
85       }) as (data: Job, filter: any) => boolean;
86     });
87
88     this.jobForm.valueChanges.subscribe((value) => {
89       this.jobsDataSource.filter = JSON.stringify(value);
90     });
91
92     this.ui.darkModeState.subscribe((isDark) => {
93       this.darkMode = isDark;
94     });
95   }
96
97   dataSubscription(): Subscription {
98     const jobsInfo$ = this.consumerService.getJobIds().pipe(
99       mergeMap((jobIds) =>
100         forkJoin(jobIds.map((jobId) => {
101           return forkJoin([
102             of(jobId),
103             this.consumerService.getJobInfo(jobId),
104             this.consumerService.getConsumerStatus(jobId)
105           ])
106         }))
107       ),
108       finalize(() => this.loadingSubject$.next(false))
109     );
110
111     const whenToRefresh$ = of('').pipe(
112       delay(10000),
113       tap((_) => this.refresh$.next('')),
114       skip(1),
115     );
116
117     const poll$ = concat(jobsInfo$, whenToRefresh$);
118
119     const refreshedJobs$ = this.refresh$.pipe(
120       tap((_) => {
121         this.loadingSubject$.next(true);
122       }),
123       concatMap((_) => this.checked ? poll$ : jobsInfo$),
124       map((response) => this.extractJobs(response))
125     );
126
127     return this.polling$
128       .pipe(
129         concatMap((value) => {
130           let pollCondition = value == 0 || this.checked;
131           return pollCondition ? refreshedJobs$ : EMPTY;
132         }),
133       )
134       .subscribe();
135   }
136
137   ngOnDestroy() {
138     this.subscription.unsubscribe();
139   }
140
141   clearFilter() {
142     this.jobForm.get("jobId").setValue("");
143     this.jobForm.get("typeId").setValue("");
144     this.jobForm.get("owner").setValue("");
145     this.jobForm.get("targetUri").setValue("");
146     this.jobForm.get("prodIds").setValue("");
147   }
148
149   sortJobs(sort: Sort) {
150     const data = this.jobsDataSource.data;
151     data.sort((a: Job, b: Job) => {
152       const isAsc = sort.direction === "asc";
153       switch (sort.active) {
154         case "jobId":
155           return this.compare(a.jobId, b.jobId, isAsc);
156         case "typeId":
157           return this.compare(a.typeId, b.typeId, isAsc);
158         case "owner":
159           return this.compare(a.owner, b.owner, isAsc);
160         case "targetUri":
161           return this.compare(a.targetUri, b.targetUri, isAsc);
162         case "prodIds":
163           return this.compare(a.prodIds, b.prodIds, isAsc);
164         default:
165           return 0;
166       }
167     });
168     this.jobsDataSource.data = data;
169   }
170
171   stopPolling(checked) {
172     this.checked = checked;
173     this.polling$.next(this.jobs().length);
174     this.refreshDataClick();
175   }
176
177   compare(a: any, b: any, isAsc: boolean) {
178     return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
179   }
180
181   stopSort(event: any) {
182     event.stopPropagation();
183   }
184
185   isDataIncluding(data: string, filter: string): boolean {
186     const transformedFilter = filter.trim().toLowerCase();
187     return data.toLowerCase().includes(transformedFilter);
188   }
189
190   isArrayIncluding(data: string[], filter: string): boolean {
191     if(!data)
192       return true;
193     for (let i = 0; i < data.length; i++) {
194       return this.isDataIncluding(data[i], filter);
195     }
196   }
197
198   getJobTypeId(job: Job): string {
199     if (job.typeId) {
200       return job.typeId;
201     }
202     return "< No type >";
203   }
204
205   getJobOwner(job: Job): string {
206     if (job.owner) {
207       return job.owner;
208     }
209     return "< No owner >";
210   }
211
212   public jobs(): Job[] {
213     return this.jobsSubject$.value;
214   }
215
216   private extractJobs(res: any) {
217     this.clearFilter();
218     let jobList = [];
219     res.forEach(element => {
220       let jobObj = <Job>{};
221       jobObj.jobId = element[0];
222       jobObj.owner = element[1].job_owner;
223       jobObj.targetUri = element[1].job_result_uri;
224       jobObj.typeId = element[1].info_type_id;
225       jobObj.prodIds = (element[2].producers) ? element[2].producers : ["No Producers"];
226       jobList = jobList.concat(jobObj);
227     });
228
229     this.jobsSubject$.next(jobList);
230     if (this.firstTime && jobList.length > 0) {
231       this.polling$.next(jobList.length);
232       this.firstTime = false;
233     }
234     return jobList;
235   }
236
237   refreshDataClick() {
238     this.refresh$.next("");
239   }
240 }