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