Angular upgrade
[osm/NG-UI.git] / src / app / projects / project-create-update / ProjectCreateUpdateComponent.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17 */
18 /**
19  * @file Project Add Modal
20  */
21 import { Component, Injector, Input, OnInit } from '@angular/core';
22 import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
23 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { NotifierService } from 'angular-notifier';
26 import { APIURLHEADER, ERRORDATA, MODALCLOSERESPONSEDATA, TYPESECTION } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { ProjectData, ProjectDetails, QUOTAITEM, QUOTA_ITEMS } from 'ProjectModel';
30 import { ProjectService } from 'ProjectService';
31 import { RestService } from 'RestService';
32 import { SharedService, isNullOrUndefined } from 'SharedService';
33
34 /**
35  * Creating component
36  * @Component takes ProjectCreateUpdateComponent.html as template url
37  */
38 @Component({
39     selector: 'app-project-create-update',
40     templateUrl: './ProjectCreateUpdateComponent.html',
41     styleUrls: ['./ProjectCreateUpdateComponent.scss']
42 })
43 /** Exporting a class @exports ProjectCreateUpdateComponent */
44 export class ProjectCreateUpdateComponent implements OnInit {
45     /** To inject services @public */
46     public injector: Injector;
47
48     /** Instance of the rest service @public */
49     public restService: RestService;
50
51     /** Instance for active modal service @public */
52     public activeModal: NgbActiveModal;
53
54     /** Contains the recently created project details @public */
55     public recentProject: ProjectDetails;
56
57     /** Contains project create or edit @public */
58     public getProjectType: string;
59
60     /** To inject input type services @public */
61     @Input() public projectType: string;
62
63     /** FormGroup user Edit Account added to the form @ html @public */
64     public projectForm: FormGroup;
65
66     /** Form submission Add */
67     public submitted: boolean = false;
68
69     /** Check the loading results for loader status @public */
70     public isLoadingResults: boolean = false;
71
72     /** Give the message for the loading @public */
73     public message: string = 'PLEASEWAIT';
74
75     /** Holds list of domains @public */
76     public domains: TYPESECTION[] = [];
77
78     /** Holds list of quota items @public */
79     public quotaItems: QUOTAITEM[] = QUOTA_ITEMS;
80
81     /** Holds project reference from response  @public */
82     public quotaRefs: {} = null;
83
84     /** FormBuilder instance added to the formBuilder @private */
85     private formBuilder: FormBuilder;
86
87     /** DataService to pass the data from one component to another @private */
88     private dataService: DataService;
89
90     /** Contains project name ref @private */
91     private projectRef: string;
92
93     /** Notifier service to popup notification @private */
94     private notifierService: NotifierService;
95
96     /** Contains tranlsate instance @private */
97     private translateService: TranslateService;
98
99     /** Contains all methods related to shared @private */
100     private sharedService: SharedService;
101
102     /** ModalData instance of modal @private  */
103     private modalData: MODALCLOSERESPONSEDATA;
104
105     /** Holds all project details @private */
106     private projectService: ProjectService;
107
108     constructor(injector: Injector) {
109         this.injector = injector;
110         this.formBuilder = this.injector.get(FormBuilder);
111         this.restService = this.injector.get(RestService);
112         this.activeModal = this.injector.get(NgbActiveModal);
113         this.dataService = this.injector.get(DataService);
114         this.notifierService = this.injector.get(NotifierService);
115         this.translateService = this.injector.get(TranslateService);
116         this.sharedService = this.injector.get(SharedService);
117         this.projectService = this.injector.get(ProjectService);
118         /** Initializing Form Action */
119         this.projectForm = this.formBuilder.group({
120             project_name: ['', Validators.required],
121             domain_name: [null],
122             enable_quota: [false, Validators.required]
123         });
124     }
125
126     /** convenience getter for easy access to form fields */
127     get f(): FormGroup['controls'] { return this.projectForm.controls; }
128
129     /** Lifecyle Hooks the trigger before component is instantiate @public */
130     public ngOnInit(): void {
131         this.getProjectType = this.projectType;
132         if (this.getProjectType === 'Edit') {
133             this.dataService.currentMessage.subscribe((data: ProjectData): void => {
134                 if (data.projectName !== undefined || data.projectName !== '' || data.projectName !== null) {
135                     this.projectForm.patchValue({ project_name: data.projectName });
136                     this.projectRef = data.id;
137                     this.quotaRefs = data.quotas;
138                     this.patchQuotaInfo(this.quotaRefs);
139                 }
140             });
141         } else {
142             this.patchQuotaInfo();
143             this.getProjects();
144         }
145     }
146
147     /** Get the last project name @public */
148     public getProjects(): void {
149         this.isLoadingResults = true;
150         this.restService.getResource(environment.PROJECTS_URL).subscribe((projects: ProjectDetails[]): void => {
151             this.recentProject = projects.slice(-1).pop();
152             this.getDomainList();
153         }, (error: ERRORDATA): void => {
154             this.restService.handleError(error, 'get');
155             this.isLoadingResults = false;
156         });
157     }
158
159     /** On modal submit users acction will called @public */
160     public projectAction(userType: string): void {
161         this.submitted = true;
162         this.modalData = {
163             message: 'Done'
164         };
165         this.sharedService.cleanForm(this.projectForm);
166         for (const data of this.quotaItems) {
167             if (this.getFormControl(data.value).value > data.maxValue) {
168                 this.notifierService.notify('error', this.translateService.instant('PAGE.PROJECT.QUOTALIMIT'));
169                 break;
170             }
171         }
172         if (!this.projectForm.invalid) {
173             if (userType === 'Add') {
174                 this.createProject();
175             } else if (userType === 'Edit') {
176                 this.editProject();
177             }
178         }
179     }
180
181     /** Create project @public */
182     public createProject(): void {
183         this.isLoadingResults = true;
184         const apiURLHeader: APIURLHEADER = {
185             url: environment.PROJECTS_URL
186         };
187         const projectPayload: ProjectDetails = {
188             name: this.projectForm.value.project_name,
189             domain_name: !isNullOrUndefined(this.projectForm.value.domain_name) ? this.projectForm.value.domain_name : undefined
190         };
191         this.addQuotaLimit(projectPayload);
192         this.restService.postResource(apiURLHeader, projectPayload).subscribe((): void => {
193             this.activeModal.close(this.modalData);
194             this.isLoadingResults = false;
195             this.notifierService.notify('success', this.translateService.instant('PAGE.PROJECT.CREATEDSUCCESSFULLY'));
196         }, (error: ERRORDATA): void => {
197             this.restService.handleError(error, 'post');
198             this.isLoadingResults = false;
199         });
200     }
201     /** Handle enable quota limit checkbox event @public */
202     public checkQuota(): void {
203         if (this.getFormControl('enable_quota').value) {
204             this.quotaItems.forEach((quotaItem: QUOTAITEM): void => {
205                 this.projectForm.addControl(quotaItem.value, new FormControl(''));
206             });
207         } else {
208             this.quotaItems.forEach((quotaItem: QUOTAITEM): void => {
209                 this.getFormControl(quotaItem.value).setValue('');
210             });
211         }
212     }
213     /** Edit project @public */
214     public editProject(): void {
215         if (!this.projectForm.dirty) {
216             this.notifierService.notify('warning', this.translateService.instant('PAGE.TOPOLOGY.DATAEMPTY'));
217             return;
218         }
219         this.isLoadingResults = true;
220         const apiURLHeader: APIURLHEADER = {
221             url: environment.PROJECTS_URL + '/' + this.projectRef
222         };
223         const projectPayload: ProjectDetails = {
224             name: this.projectForm.value.project_name
225         };
226         this.addQuotaLimit(projectPayload);
227         this.restService.patchResource(apiURLHeader, projectPayload).subscribe((): void => {
228             this.activeModal.close(this.modalData);
229             this.isLoadingResults = false;
230             this.projectService.setHeaderProjects();
231             this.notifierService.notify('success', this.translateService.instant('PAGE.PROJECT.UPDATEDSUCCESSFULLY'));
232             this.activeModal.close(this.modalData);
233         }, (error: ERRORDATA): void => {
234             this.restService.handleError(error, 'patch');
235             this.isLoadingResults = false;
236         });
237     }
238     /** Get domain name list @private */
239     private getDomainList(): void {
240         this.isLoadingResults = true;
241         this.sharedService.getDomainName().subscribe((domainList: TYPESECTION[]): void => {
242             this.domains = domainList;
243             this.isLoadingResults = false;
244         }, (error: ERRORDATA): void => {
245             this.isLoadingResults = false;
246             this.restService.handleError(error, 'get');
247         });
248     }
249
250     /** Used to get the AbstractControl of controlName passed @private */
251     private getFormControl(controlName: string): AbstractControl {
252         // eslint-disable-next-line security/detect-object-injection
253         return this.projectForm.controls[controlName];
254     }
255
256     /** Add quota information to payload @private */
257     private addQuotaLimit(payload: ProjectDetails): void {
258         if (this.getFormControl('enable_quota').value) {
259             payload.quotas = {};
260             this.quotaItems.forEach((quotaItem: QUOTAITEM): void => {
261                 if (this.getFormControl(quotaItem.value).value !== '') {
262                     payload.quotas[quotaItem.value] = this.getFormControl(quotaItem.value).value;
263                 }
264             });
265             if (Object.keys(payload.quotas).length === 0) {
266                 delete payload.quotas;
267             }
268         }
269     }
270
271     /** Set quota information in project form model @private */
272     private patchQuotaInfo(quotaRef?: {}): void {
273         if (quotaRef !== null && this.getProjectType === 'Edit') {
274             this.getFormControl('enable_quota').setValue(true);
275             this.quotaItems.forEach((quotaItem: QUOTAITEM): void => {
276                 if (!isNullOrUndefined(quotaRef[quotaItem.value])) {
277                     this.projectForm.addControl(quotaItem.value, new FormControl(quotaRef[quotaItem.value],
278                         [Validators.max(quotaItem.maxValue)]));
279                 } else {
280                     this.projectForm.addControl(quotaItem.value, new FormControl('', [Validators.max(quotaItem.maxValue)]));
281                 }
282             });
283         } else {
284             this.quotaItems.forEach((quotaItem: QUOTAITEM): void => {
285                 this.projectForm.addControl(quotaItem.value, new FormControl('', [Validators.min(quotaItem.minValue),
286                 Validators.max(quotaItem.maxValue)]));
287             });
288         }
289     }
290 }