d9885489f434ec56716db3d7747776e112af29f5
[osm/NG-UI.git] / src / app / users / add-user / AddEditUserComponent.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 Add Edit Component.
20  */
21 import { HttpHeaders } from '@angular/common/http';
22 import { Component, Injector, Input, OnInit } from '@angular/core';
23 import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
25 import { TranslateService } from '@ngx-translate/core';
26 import { NotifierService } from 'angular-notifier';
27 import { AuthenticationService } from 'AuthenticationService';
28 import { APIURLHEADER, ERRORDATA, LOGINPARAMS, MODALCLOSERESPONSEDATA, TYPESECTION } from 'CommonModel';
29 import { environment } from 'environment';
30 import { RestService } from 'RestService';
31 import { SharedService } from 'SharedService';
32 import { isNullOrUndefined } from 'util';
33
34 /**
35  * Creating component
36  * @Component takes AddEditUserComponent.html as template url
37  */
38 @Component({
39     templateUrl: './AddEditUserComponent.html',
40     styleUrls: ['./AddEditUserComponent.scss']
41 })
42 /** Exporting a class @exports AddEditUserComponent */
43 export class AddEditUserComponent implements OnInit {
44     /** To inject services @public */
45     public injector: Injector;
46
47     /** Instance for active modal service @public */
48     public activeModal: NgbActiveModal;
49
50     /** FormGroup user Edit Account added to the form @ html @public */
51     public userForm: FormGroup;
52
53     /** Form submission Add */
54     public submitted: boolean = false;
55
56     /** Input contains Modal dialog component Instance @public */
57     @Input() public userTitle: string;
58
59     /** Input contains Modal dialog component Instance @public */
60     @Input() public userType: string;
61
62     /** Input contains Modal dialog component Instance @public */
63     @Input() public userID: string;
64
65     /** Input contains Modal dialog component Instance @public */
66     @Input() public userName: string;
67
68     /** Check the loading results for loader status @public */
69     public isLoadingResults: boolean = false;
70
71     /** Give the message for the loading @public */
72     public message: string = 'PLEASEWAIT';
73
74     /** Holds list of domains @public */
75     public domains: TYPESECTION[] = [];
76
77     /** Instance of the rest service @private */
78     private restService: RestService;
79
80     /** FormBuilder instance added to the formBuilder @private */
81     private formBuilder: FormBuilder;
82
83     /** Controls the header form @private */
84     private headers: HttpHeaders;
85
86     /** Notifier service to popup notification @private */
87     private notifierService: NotifierService;
88
89     /** Contains tranlsate instance @private */
90     private translateService: TranslateService;
91
92     /** Contains all methods related to shared @private */
93     private sharedService: SharedService;
94
95     /** ModalData instance of modal @private  */
96     private modalData: MODALCLOSERESPONSEDATA;
97
98     /** Utilizes auth service for any auth operations @private */
99     private authService: AuthenticationService;
100
101     constructor(injector: Injector) {
102         this.injector = injector;
103         this.formBuilder = this.injector.get(FormBuilder);
104         this.restService = this.injector.get(RestService);
105         this.activeModal = this.injector.get(NgbActiveModal);
106         this.notifierService = this.injector.get(NotifierService);
107         this.translateService = this.injector.get(TranslateService);
108         this.sharedService = this.injector.get(SharedService);
109         this.authService = this.injector.get(AuthenticationService);
110
111         /** Initializing Form Action */
112         this.userForm = this.formBuilder.group({
113             userName: ['', Validators.required],
114             password: [null, [Validators.required, Validators.pattern(this.sharedService.REGX_PASSWORD_PATTERN)]],
115             password2: [null, Validators.required],
116             domain_name: [null]
117         });
118     }
119
120     /** convenience getter for easy access to form fields */
121     get f(): FormGroup['controls'] { return this.userForm.controls; }
122
123     /** Lifecyle Hooks the trigger before component is instantiate @public */
124     public ngOnInit(): void {
125         this.headers = new HttpHeaders({
126             'Content-Type': 'application/json',
127             Accept: 'application/json',
128             'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0'
129         });
130         if (this.userType === 'add') {
131             this.getDomainList();
132         } else if (this.userType === 'editUserName') {
133             this.userForm.patchValue({ userName: this.userName });
134         }
135     }
136
137     /** On modal submit users acction will called @public */
138     public userAction(userType: string): void {
139         if (userType === 'editPassword') {
140             this.getFormControl('userName').setValidators([]);
141             this.getFormControl('userName').updateValueAndValidity();
142         } else if (userType === 'editUserName') {
143             this.getFormControl('password').setValidators([]);
144             this.getFormControl('password').updateValueAndValidity();
145             this.getFormControl('password2').setValidators([]);
146             this.getFormControl('password2').updateValueAndValidity();
147         }
148         this.submitted = true;
149         this.modalData = {
150             message: 'Done'
151         };
152         this.sharedService.cleanForm(this.userForm);
153         if (!this.userForm.invalid) {
154             if (this.userForm.value.password !== this.userForm.value.password2) {
155                 this.notifierService.notify('error', this.translateService.instant('PAGE.USERS.PASSWORDCONFLICT'));
156                 return;
157             }
158             if (userType === 'add') {
159                 this.addUser();
160             } else if (userType === 'editUserName' || userType === 'editPassword') {
161                 this.editUser();
162             }
163         }
164     }
165
166     /** Add user @public */
167     public addUser(): void {
168         this.isLoadingResults = true;
169         const payLoad: {} = JSON.stringify({
170             username: (this.userForm.value.userName).toLowerCase(),
171             password: (this.userForm.value.password),
172             domain_name: !isNullOrUndefined(this.userForm.value.domain_name) ? this.userForm.value.domain_name : undefined
173         });
174         const apiURLHeader: APIURLHEADER = {
175             url: environment.USERS_URL,
176             httpOptions: { headers: this.headers }
177         };
178         this.restService.postResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
179             this.activeModal.close(this.modalData);
180             this.isLoadingResults = false;
181             this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CREATEDSUCCESSFULLY'));
182         }, (error: ERRORDATA): void => {
183             this.restService.handleError(error, 'post');
184             this.isLoadingResults = false;
185         });
186     }
187
188     /** Edit user @public */
189     public editUser(): void {
190         this.isLoadingResults = true;
191         const payLoad: LOGINPARAMS = {};
192         if (this.userType === 'editPassword') {
193             payLoad.password = (this.userForm.value.password);
194         } else {
195             payLoad.username = this.userForm.value.userName.toLowerCase();
196         }
197         const apiURLHeader: APIURLHEADER = {
198             url: environment.USERS_URL + '/' + this.userID,
199             httpOptions: { headers: this.headers }
200         };
201         this.restService.patchResource(apiURLHeader, payLoad).subscribe((result: {}): void => {
202             this.checkUsername(payLoad);
203             this.activeModal.close(this.modalData);
204             this.isLoadingResults = false;
205             this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.EDITEDSUCCESSFULLY'));
206         }, (error: ERRORDATA): void => {
207             this.restService.handleError(error, 'put');
208             this.isLoadingResults = false;
209         });
210     }
211     /** Get domain name list @private */
212     private getDomainList(): void {
213         this.isLoadingResults = true;
214         this.sharedService.getDomainName().subscribe((domainList: TYPESECTION[]): void => {
215             this.domains = domainList;
216             this.isLoadingResults = false;
217         }, (error: ERRORDATA): void => {
218             this.isLoadingResults = false;
219             this.restService.handleError(error, 'get');
220         });
221     }
222
223     /** Used to get the AbstractControl of controlName passed @private */
224     private getFormControl(controlName: string): AbstractControl {
225         return this.userForm.controls[controlName];
226     }
227
228     /** Method to check loggedin username and update  @private */
229     private checkUsername(payLoad: LOGINPARAMS): void {
230         const logUsername: string = localStorage.getItem('username');
231         if (this.userType === 'editUserName' && logUsername === this.userName) {
232             this.authService.userName.next(payLoad.username);
233             localStorage.setItem('username', payLoad.username);
234         }
235     }
236 }