Small modifications to instance dialogs
[portal/nonrtric-controlpanel.git] / webapp-frontend / src / app / policy-control / policy-instance-dialog.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 import { animate, state, style, transition, trigger } from '@angular/animations';
21 import { AfterViewInit, Component, Inject, OnInit, ViewChild } from '@angular/core';
22 import { MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
23 import { MatMenuTrigger } from '@angular/material/menu';
24 import { JsonPointer } from 'angular6-json-schema-form';
25 import * as uuid from 'uuid';
26 import { PolicyInstance, PolicyType } from '../interfaces/policy.types';
27 import { PolicyService } from '../services/policy/policy.service';
28 import { ErrorDialogService } from '../services/ui/error-dialog.service';
29 import { NotificationService } from './../services/ui/notification.service';
30 import { UiService } from '../services/ui/ui.service';
31 import { HttpErrorResponse } from '@angular/common/http';
32 import { FormGroup, FormControl, Validators } from '@angular/forms';
33
34
35 @Component({
36     selector: 'rd-policy-instance-dialog',
37     templateUrl: './policy-instance-dialog.component.html',
38     styleUrls: ['./policy-instance-dialog.component.scss'],
39     animations: [
40         trigger('expandSection', [
41             state('in', style({ height: '*' })),
42             transition(':enter', [
43                 style({ height: 0 }), animate(100),
44             ]),
45             transition(':leave', [
46                 style({ height: '*' }),
47                 animate(100, style({ height: 0 })),
48             ]),
49         ]),
50     ],
51 })
52 export class PolicyInstanceDialogComponent implements OnInit, AfterViewInit {
53     instanceForm: FormGroup;
54
55
56     formActive = false;
57     isVisible = {
58         form: true,
59         json: false,
60         schema: false
61     };
62
63     jsonFormStatusMessage = 'Loading form...';
64     jsonSchemaObject: any = {};
65     jsonObject: any = {};
66
67
68     jsonFormOptions: any = {
69         addSubmit: false, // Add a submit button if layout does not have one
70         debug: false, // Don't show inline debugging information
71         loadExternalAssets: true, // Load external css and JavaScript for frameworks
72         returnEmptyFields: false, // Don't return values for empty input fields
73         setSchemaDefaults: true, // Always use schema defaults for empty fields
74         defautWidgetOptions: { feedback: true }, // Show inline feedback icons
75     };
76
77     liveFormData: any = {};
78     formValidationErrors: any;
79     formIsValid = false;
80
81     @ViewChild(MatMenuTrigger, { static: true }) menuTrigger: MatMenuTrigger;
82
83     policyInstanceId: string; // null if not yet created
84     policyTypeName: string;
85     darkMode: boolean;
86     ric: string;
87     allRics: string[];
88
89     private fetchRics() {
90         console.log('fetchRics ' + this.policyTypeName);
91         const self: PolicyInstanceDialogComponent = this;
92         this.dataService.getRics(this.policyTypeName).subscribe(
93             {
94                 next(value) {
95                     self.allRics = value;
96                     console.log(value);
97                 },
98                 error(error: HttpErrorResponse) {
99                     self.errorService.displayError('Fetching of rics failed: ' + error.message);
100                 },
101                 complete() { }
102             });
103     }
104
105     constructor(
106         private dataService: PolicyService,
107         private errorService: ErrorDialogService,
108         private notificationService: NotificationService,
109         @Inject(MAT_DIALOG_DATA) private data,
110         private dialogRef: MatDialogRef<PolicyInstanceDialogComponent>,
111         private ui: UiService) {
112         this.formActive = false;
113         this.policyInstanceId = data.instanceId;
114         this.policyTypeName = data.name;
115         this.jsonSchemaObject = data.createSchema;
116         this.jsonObject = this.parseJson(data.instanceJson);
117         this.ric = data.ric;
118     }
119
120     ngOnInit() {
121         this.jsonFormStatusMessage = 'Init';
122         this.formActive = true;
123         this.ui.darkModeState.subscribe((isDark) => {
124             this.darkMode = isDark;
125         });
126         this.instanceForm = new FormGroup({
127             'ricSelector': new FormControl(this.ric, [
128                 Validators.required
129             ])
130         });
131         if (!this.policyInstanceId) {
132             this.fetchRics();
133         }
134     }
135
136     ngAfterViewInit() {
137     }
138
139     onSubmit() {
140         if (this.policyInstanceId == null) {
141             this.policyInstanceId = uuid.v4();
142         }
143         const policyJson: string = this.prettyLiveFormData;
144         const self: PolicyInstanceDialogComponent = this;
145         this.dataService.putPolicy(this.policyTypeName, this.policyInstanceId, policyJson, this.ric).subscribe(
146             {
147                 next(_) {
148                     self.notificationService.success('Policy ' + self.policyTypeName + ':' + self.policyInstanceId +
149                     ' submitted');
150                 },
151                 error(error: HttpErrorResponse) {
152                     self.errorService.displayError('Submit failed: ' + error.error);
153                 },
154                 complete() { }
155             });
156     }
157
158     onClose() {
159         this.dialogRef.close();
160     }
161
162     public onChanges(formData: any) {
163         this.liveFormData = formData;
164     }
165
166     get prettyLiveFormData(): string {
167         return JSON.stringify(this.liveFormData, null, 2);
168     }
169
170     get schemaAsString(): string {
171         return JSON.stringify(this.jsonSchemaObject, null, 2);
172     }
173
174     get jsonAsString(): string {
175         return JSON.stringify(this.jsonObject, null, 2);
176     }
177
178     isValid(isValid: boolean): void {
179         this.formIsValid = isValid;
180     }
181
182     validationErrors(validationErrors: any): void {
183         this.formValidationErrors = validationErrors;
184     }
185
186     get prettyValidationErrors() {
187         if (!this.formValidationErrors) { return null; }
188         const errorArray = [];
189         for (const error of this.formValidationErrors) {
190             const message = error.message;
191             const dataPathArray = JsonPointer.parse(error.dataPath);
192             if (dataPathArray.length) {
193                 let field = dataPathArray[0];
194                 for (let i = 1; i < dataPathArray.length; i++) {
195                     const key = dataPathArray[i];
196                     field += /^\d+$/.test(key) ? `[${key}]` : `.${key}`;
197                 }
198                 errorArray.push(`${field}: ${message}`);
199             } else {
200                 errorArray.push(message);
201             }
202         }
203         return errorArray.join('<br>');
204     }
205
206     private parseJson(str: string): string {
207         try {
208             if (str != null) {
209                 return JSON.parse(str);
210             }
211         } catch (jsonError) {
212             this.jsonFormStatusMessage =
213                 'Invalid JSON\n' +
214                 'parser returned:\n\n' + jsonError;
215         }
216         return null;
217     }
218
219     public toggleVisible(item: string) {
220         this.isVisible[item] = !this.isVisible[item];
221     }
222 }
223
224 export function getPolicyDialogProperties(policyType: PolicyType, instance: PolicyInstance, darkMode: boolean): MatDialogConfig {
225     const createSchema = policyType.schemaObject;
226     const instanceId = instance ? instance.id : null;
227     const instanceJson = instance ? instance.json : null;
228     const name = policyType.name;
229     const ric = instance ? instance.ric : null;
230     return {
231         maxWidth: '1200px',
232         maxHeight: '900px',
233         width: '900px',
234         role: 'dialog',
235         disableClose: false,
236         panelClass: darkMode ? 'dark-theme' : '',
237         data: {
238             createSchema,
239             instanceId,
240             instanceJson,
241             name,
242             ric
243         }
244     };
245 }
246