24a7cc7a9cdfddc724f4612cd8745607783cc11d
[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         let schemaId = this.policyTypeSchema.id;
79         if(schemaId.includes('<No Type>')){
80             schemaId = '';
81         }
82         this.policyInstanceDataSource = new PolicyInstanceDataSource(this.policySvc, this.sort, this.notificationService, schemaId);
83         this.expanded.subscribe((isExpanded: boolean) => this.onExpand(isExpanded));
84
85         this.policyInstanceDataSource.connect().subscribe((data) => {
86             this.instanceDataSource.data = data;
87         })
88
89         this.policyInstanceForm.valueChanges.subscribe(value => {
90             const filter = {...value, id: value.id.trim().toLowerCase()} as string;
91             this.instanceDataSource.filter = filter;
92         });
93
94         this.instanceDataSource.filterPredicate = ((data: PolicyInstance, filter) => {
95             return this.isDataIncluding(data.policy_id, filter.id)
96                 && this.isDataIncluding(data.ric_id, filter.target)
97                 && this.isDataIncluding(data.service_id, filter.owner)
98                 && this.isDataIncluding(data.lastModified, filter.lastModified);
99           }) as (data: PolicyInstance, filter: any) => boolean;
100
101         this.ui.darkModeState.subscribe((isDark) => {
102             this.darkMode = isDark;
103         });
104     }
105
106     compare(a: any, b: any, isAsc: boolean) {
107       return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
108     }
109
110     stopSort(event: any){
111         event.stopPropagation();
112     }
113
114     isDataIncluding(data: string, filter: string) : boolean {
115         return !filter || data.toLowerCase().includes(filter);
116     }
117
118     ngAfterViewInit() {
119         this.policyInstanceDataSource.sort = this.sort;
120     }
121
122     private onExpand(isExpanded: boolean) {
123         if (isExpanded) {
124             this.policyInstanceDataSource.getPolicyInstances();
125         }
126     }
127
128     private isSchemaEmpty(): boolean {
129         return this.policyTypeSchema.schemaObject === '{}';
130     }
131
132     modifyInstance(instance: PolicyInstance): void {
133         this.policySvc.getPolicyInstance(instance.policy_id).subscribe(
134             (refreshedJson: any) => {
135                 instance = refreshedJson;
136                 this.dialog.open(
137                     PolicyInstanceDialogComponent,
138                     getPolicyDialogProperties(this.policyTypeSchema, instance, this.darkMode)).afterClosed().subscribe(
139                         (_: any) => {
140                             this.policyInstanceDataSource.getPolicyInstances();
141                         }
142                     );
143             },
144             (httpError: HttpErrorResponse) => {
145                 this.notificationService.error('Could not refresh instance. Please try again.' + httpError.message);
146             }
147         );
148     }
149
150     hasInstances(): boolean {
151         return this.policyInstanceDataSource.rowCount > 0;
152     }
153
154     nbInstances(): number {
155         return this.policyInstanceDataSource.policyInstances.length;
156     }
157
158     toLocalTime(utcTime: string): string {
159         const date = new Date(utcTime);
160         const toutc = date.toUTCString();
161         return new Date(toutc + ' UTC').toLocaleString();
162
163     }
164
165     createPolicyInstance(policyTypeSchema: PolicyTypeSchema): void {
166         let dialogRef = this.dialog.open(PolicyInstanceDialogComponent,
167             getPolicyDialogProperties(policyTypeSchema, null, this.darkMode));
168         const info: PolicyTypeInfo = this.getPolicyTypeInfo(policyTypeSchema);
169         dialogRef.afterClosed().subscribe(
170             (_) => {
171                 info.isExpanded.next(info.isExpanded.getValue());
172             }
173         );
174     }
175
176     deleteInstance(instance: PolicyInstance): void {
177         this.confirmDialogService
178             .openConfirmDialog('Are you sure you want to delete this policy instance?')
179             .afterClosed().subscribe(
180                 (res: any) => {
181                     if (res) {
182                         this.policySvc.deletePolicy(instance.policy_id)
183                             .subscribe(
184                                 (response: HttpResponse<Object>) => {
185                                     switch (response.status) {
186                                         case 204:
187                                             this.notificationService.success('Delete succeeded!');
188                                             this.policyInstanceDataSource.getPolicyInstances();
189                                             break;
190                                         default:
191                                             this.notificationService.warn('Delete failed ' + response.status + ' ' + response.body);
192                                     }
193                                 },
194                                 (error: HttpErrorResponse) => {
195                                     this.errorDialogService.displayError(error.statusText + ', ' + error.error);
196                                 });
197                     }
198                 });
199     }
200
201     getPolicyTypeInfo(policyTypeSchema: PolicyTypeSchema): PolicyTypeInfo {
202         let info: PolicyTypeInfo = this.policyTypeInfo.get(policyTypeSchema.name);
203         if (!info) {
204             info = new PolicyTypeInfo(policyTypeSchema);
205             this.policyTypeInfo.set(policyTypeSchema.name, info);
206         }
207         return info;
208     }
209
210     refreshTable() {
211         this.policyInstanceDataSource.getPolicyInstances();
212     }
213 }