700e929728ff1dd1fa0b7ec836898cc6d16387cd
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy / policy-instance / policy-instance.component.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 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
21 import { MatSort, Sort } from '@angular/material/sort';
22 import { Component, OnInit, ViewChild, Input, AfterViewInit } from '@angular/core';
23 import { MatDialog } from '@angular/material/dialog';
24 import { PolicyTypeSchema } from '@interfaces/policy.types';
25 import { PolicyInstanceDataSource } from './policy-instance.datasource';
26 import { ErrorDialogService } from '@services/ui/error-dialog.service';
27 import { NotificationService } from '@services/ui/notification.service';
28 import { PolicyService } from '@services/policy/policy.service';
29 import { ConfirmDialogService } from '@services/ui/confirm-dialog.service';
30 import { PolicyInstance } from '@interfaces/policy.types';
31 import { PolicyInstanceDialogComponent } from '../policy-instance-dialog/policy-instance-dialog.component';
32 import { getPolicyDialogProperties } from '../policy-instance-dialog/policy-instance-dialog.component';
33 import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
34 import { BehaviorSubject, Observable } from 'rxjs';
35 import { UiService } from '@services/ui/ui.service';
36 import { FormControl, FormGroup } from '@angular/forms';
37 import { MatTableDataSource } from '@angular/material/table';
38
39 class PolicyTypeInfo {
40   constructor(public type: PolicyTypeSchema) { }
41
42   isExpanded: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
43 }
44
45 @Component({
46     selector: 'nrcp-policy-instance',
47     templateUrl: './policy-instance.component.html',
48     styleUrls: ['./policy-instance.component.scss']
49 })
50
51
52 export class PolicyInstanceComponent implements OnInit, AfterViewInit {
53     policyInstanceDataSource: PolicyInstanceDataSource;
54     @Input() policyTypeSchema: PolicyTypeSchema;
55     @Input() expanded: Observable<boolean>;
56     @ViewChild(MatSort, { static: true }) sort: MatSort;
57     policyTypeInfo = new Map<string, PolicyTypeInfo>();
58     instanceDataSource: MatTableDataSource<PolicyInstance> = new MatTableDataSource<PolicyInstance>();
59     policyInstanceForm: FormGroup;
60     darkMode: boolean;
61
62     constructor(
63         private policySvc: PolicyService,
64         private dialog: MatDialog,
65         private errorDialogService: ErrorDialogService,
66         private notificationService: NotificationService,
67         private confirmDialogService: ConfirmDialogService,
68         private ui: UiService) {
69             this.policyInstanceForm = new FormGroup({
70                 id: new FormControl(''),
71                 target: new FormControl(''),
72                 owner: new FormControl(''),
73                 lastModified: new FormControl('')
74             })
75     }
76
77     ngOnInit() {
78         this.policyInstanceDataSource = new PolicyInstanceDataSource(this.policySvc, this.sort, this.notificationService, this.policyTypeSchema.id);
79         this.expanded.subscribe((isExpanded: boolean) => this.onExpand(isExpanded));
80
81         this.policyInstanceDataSource.connect().subscribe((data) => {
82             this.instanceDataSource.data = data;
83         })
84
85         this.policyInstanceForm.valueChanges.subscribe(value => {
86             const filter = {...value, id: value.id.trim().toLowerCase()} as string;
87             this.instanceDataSource.filter = filter;
88         });
89
90         this.instanceDataSource.filterPredicate = ((data: PolicyInstance, filter) => {
91             return this.isDataIncluding(data.policy_id, filter.id)
92                 && this.isDataIncluding(data.ric_id, filter.target)
93                 && this.isDataIncluding(data.service_id, filter.owner)
94                 && this.isDataIncluding(data.lastModified, filter.lastModified);
95           }) as (data: PolicyInstance, filter: any) => boolean;
96
97         this.ui.darkModeState.subscribe((isDark) => {
98             this.darkMode = isDark;
99         });
100     }
101
102     compare(a: any, b: any, isAsc: boolean) {
103       return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
104     }
105
106     stopSort(event: any){
107         event.stopPropagation();
108     }
109
110     isDataIncluding(data: string, filter: string) : boolean {
111         return !filter || data.toLowerCase().includes(filter);
112     }
113
114     ngAfterViewInit() {
115         this.policyInstanceDataSource.sort = this.sort;
116     }
117
118     private onExpand(isExpanded: boolean) {
119         if (isExpanded) {
120             this.policyInstanceDataSource.getPolicyInstances();
121         }
122     }
123
124     private isSchemaEmpty(): boolean {
125         return this.policyTypeSchema.schemaObject === '{}';
126     }
127
128     modifyInstance(instance: PolicyInstance): void {
129         this.policySvc.getPolicyInstance(instance.policy_id).subscribe(
130             (refreshedJson: any) => {
131                 instance = refreshedJson;
132                 this.dialog.open(
133                     PolicyInstanceDialogComponent,
134                     getPolicyDialogProperties(this.policyTypeSchema, instance, this.darkMode)).afterClosed().subscribe(
135                         (_: any) => {
136                             this.policyInstanceDataSource.getPolicyInstances();
137                         }
138                     );
139             },
140             (httpError: HttpErrorResponse) => {
141                 this.notificationService.error('Could not refresh instance. Please try again.' + httpError.message);
142             }
143         );
144     }
145
146     hasInstances(): boolean {
147         return this.policyInstanceDataSource.rowCount > 0;
148     }
149
150     nbInstances(): number {
151         return this.policyInstanceDataSource.policyInstances.length;
152     }
153
154     toLocalTime(utcTime: string): string {
155         const date = new Date(utcTime);
156         const toutc = date.toUTCString();
157         return new Date(toutc + ' UTC').toLocaleString();
158
159     }
160
161     createPolicyInstance(policyTypeSchema: PolicyTypeSchema): void {
162         let dialogRef = this.dialog.open(PolicyInstanceDialogComponent,
163             getPolicyDialogProperties(policyTypeSchema, null, this.darkMode));
164         const info: PolicyTypeInfo = this.getPolicyTypeInfo(policyTypeSchema);
165         dialogRef.afterClosed().subscribe(
166             (_) => {
167                 info.isExpanded.next(info.isExpanded.getValue());
168             }
169         );
170     }
171
172     deleteInstance(instance: PolicyInstance): void {
173         this.confirmDialogService
174             .openConfirmDialog('Are you sure you want to delete this policy instance?')
175             .afterClosed().subscribe(
176                 (res: any) => {
177                     if (res) {
178                         this.policySvc.deletePolicy(instance.policy_id)
179                             .subscribe(
180                                 (response: HttpResponse<Object>) => {
181                                     switch (response.status) {
182                                         case 204:
183                                             this.notificationService.success('Delete succeeded!');
184                                             this.policyInstanceDataSource.getPolicyInstances();
185                                             break;
186                                         default:
187                                             this.notificationService.warn('Delete failed ' + response.status + ' ' + response.body);
188                                     }
189                                 },
190                                 (error: HttpErrorResponse) => {
191                                     this.errorDialogService.displayError(error.statusText + ', ' + error.error);
192                                 });
193                     }
194                 });
195     }
196
197     getPolicyTypeInfo(policyTypeSchema: PolicyTypeSchema): PolicyTypeInfo {
198         let info: PolicyTypeInfo = this.policyTypeInfo.get(policyTypeSchema.name);
199         if (!info) {
200             info = new PolicyTypeInfo(policyTypeSchema);
201             this.policyTypeInfo.set(policyTypeSchema.name, info);
202         }
203         return info;
204     }
205
206     refreshTable() {
207         this.policyInstanceDataSource.getPolicyInstances();
208     }
209 }