Initial Commit - NG UI
[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, MODALCLOSERESPONSEDATA } 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: {}[] = [];
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.getDomainName();
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: {}) => {
179       this.activeModal.close(this.modalData);
180       this.isLoadingResults = false;
181       this.notifierService.notify('success', this.translateService.instant('PAGE.USERS.CREATEDSUCCESSFULLY'));
182     }, (error: ERRORDATA) => {
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: { username?: string, password?: string } = {};
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: {}) => {
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) => {
207       this.restService.handleError(error, 'put');
208       this.isLoadingResults = false;
209     });
210   }
211   /** Get domain name @private */
212   private getDomainName(): void {
213     this.isLoadingResults = true;
214     this.restService.getResource(environment.DOMAIN_URL).subscribe((domains: { project_domain_name: string, user_domain_name: string }) => {
215       let domainNames: string[] = [];
216       if (!isNullOrUndefined(domains.project_domain_name)) {
217         domainNames = domainNames.concat(domains.project_domain_name.split(','));
218       }
219       if (!isNullOrUndefined(domains.user_domain_name)) {
220         domainNames = domainNames.concat(domains.user_domain_name.split(','));
221       }
222       domainNames = Array.from(new Set(domainNames));
223       this.checkDomainNames(domainNames);
224       this.isLoadingResults = false;
225     }, (error: ERRORDATA) => {
226       this.restService.handleError(error, 'get');
227       this.isLoadingResults = false;
228     });
229   }
230
231   /** Check the domain names and create modal for domain select @private */
232   private checkDomainNames(domainNames: string[]): void {
233     if (domainNames.length > 0) {
234       domainNames.forEach((domainName: string) => {
235         if (!domainName.endsWith(':ro')) {
236           this.domains.push({ id: domainName, text: domainName });
237         }
238       });
239     }
240   }
241
242   /** Used to get the AbstractControl of controlName passed @private */
243   private getFormControl(controlName: string): AbstractControl {
244     return this.userForm.controls[controlName];
245   }
246
247   /** Method to check loggedin username and update  @private */
248   private checkUsername(payLoad: { username?: string }): void {
249     const logUsername: string = localStorage.getItem('username');
250     if (this.userType === 'editUserName' && logUsername === this.userName) {
251       this.authService.userName.next(payLoad.username);
252       localStorage.setItem('username', payLoad.username);
253     }
254   }
255 }