Angular upgrade
[osm/NG-UI.git] / src / app / users / user-details / UserDetailsComponent.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 /* eslint-disable security/detect-object-injection */
19 /**
20  * @file users details Component.
21  */
22 import { Component, Injector, OnDestroy, OnInit } from '@angular/core';
23 import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
24 import { TranslateService } from '@ngx-translate/core';
25 import { AddEditUserComponent } from 'AddEditUserComponent';
26 import { CONFIGCONSTANT, ERRORDATA, MODALCLOSERESPONSEDATA } from 'CommonModel';
27 import { DataService } from 'DataService';
28 import { environment } from 'environment';
29 import { LocalDataSource } from 'ng2-smart-table';
30 import { ProjectService } from 'ProjectService';
31 import { RestService } from 'RestService';
32 import { Subscription } from 'rxjs';
33 import { SharedService, isNullOrUndefined } from 'SharedService';
34 import { UserData, UserDetail } from 'UserModel';
35 import { UsersActionComponent } from 'UsersActionComponent';
36
37 /**
38  * Creating component
39  * @Component takes UserDetailsComponent.html as template url
40  */
41 @Component({
42   templateUrl: './UserDetailsComponent.html',
43   styleUrls: ['./UserDetailsComponent.scss']
44 })
45 /** Exporting a class @exports UserDetailsComponent */
46 export class UserDetailsComponent implements OnInit, OnDestroy {
47   /** Data of smarttable populate through LocalDataSource @public */
48   public dataSource: LocalDataSource = new LocalDataSource();
49
50   /** handle translate @public */
51   public translateService: TranslateService;
52
53   /** To inject services @public */
54   public injector: Injector;
55
56   /** Settings for smarttable to populate the table with columns @public */
57   public settings: object = {};
58
59   /** Check the loading results @public */
60   public isLoadingResults: boolean = true;
61
62   /** Give the message for the loading @public */
63   public message: string = 'PLEASEWAIT';
64
65   /** Class for empty and present data @public */
66   public checkDataClass: string;
67
68   /** user active data @public */
69   public userActive: string = CONFIGCONSTANT.userActive;
70
71   /** user locked data @public */
72   public userLocked: string = CONFIGCONSTANT.userLocked;
73
74   /** user expired data @public */
75   public userExpired: string = CONFIGCONSTANT.userExpired;
76
77   /** user always-active data @public */
78   public userAlwaysActive: string = CONFIGCONSTANT.userAlwaysActive;
79
80   /** Admin Visibility Check  @public */
81   public isAdminShow: boolean;
82
83   /** Instance of the rest service @private */
84   private restService: RestService;
85
86   /** dataService to pass the data from one component to another @private */
87   private dataService: DataService;
88
89   /** Instance of the modal service @private */
90   private modalService: NgbModal;
91
92   /** Formation of appropriate Data for LocalDatasource @private */
93   private userData: {}[] = [];
94
95   /** Contains all methods related to shared @private */
96   private sharedService: SharedService;
97
98   /** Holds all project details */
99   private projectService: ProjectService;
100
101   /** holds the project information @private */
102   private projectList: {}[] = [];
103
104   /** Columns list of the smart table @public */
105   private columnLists: object = {};
106
107   /** Instance of subscriptions @private */
108   private generateDataSub: Subscription;
109
110   constructor(injector: Injector) {
111     this.injector = injector;
112     this.restService = this.injector.get(RestService);
113     this.dataService = this.injector.get(DataService);
114     this.sharedService = this.injector.get(SharedService);
115     this.modalService = this.injector.get(NgbModal);
116     this.projectService = this.injector.get(ProjectService);
117     this.translateService = this.injector.get(TranslateService);
118   }
119
120   /**
121    * Lifecyle Hooks the trigger before component is instantiate
122    */
123   public ngOnInit(): void {
124     this.projectService.getAllProjects().subscribe((projects: {}[]) => {
125       this.projectList = projects;
126     });
127     this.isAdminShow = sessionStorage.getItem('admin_show') === 'true' ? true : false;
128     this.generateColumns();
129     this.generateSettings();
130     this.generateData();
131     this.hideColumnForUser();
132     this.generateDataSub = this.sharedService.dataEvent.subscribe(() => { this.generateData(); });
133   }
134
135   /** smart table Header Colums @public */
136   public generateColumns(): void {
137     this.columnLists = {
138       username: { title: this.translateService.instant('NAME'), width: '10%', sortDirection: 'asc' },
139       projects: { title: this.translateService.instant('PAGE.DASHBOARD.PROJECTS'), width: '15%' },
140       identifier: { title: this.translateService.instant('IDENTIFIER'), width: '10%' },
141       user_status: {
142         type: 'html',
143         title: this.translateService.instant('STATUS'),
144         width: '15%',
145         filter: {
146           type: 'list',
147           config: {
148             selectText: 'Select',
149             list: [
150               { value: this.userActive, title: this.userActive },
151               { value: this.userLocked, title: this.userLocked },
152               { value: this.userExpired, title: this.userExpired },
153               { value: this.userAlwaysActive, title: this.userAlwaysActive }
154             ]
155           }
156         },
157         valuePrepareFunction: (cell: UserData, row: UserData): string => {
158           if (row.user_status === this.userActive) {
159             return `<span class="icon-label" title="${row.user_status}">
160                  <i class="fas fa-user-check text-success"></i>
161                  </span>`;
162           } else if (row.user_status === this.userLocked) {
163             return `<span class="icon-label" title="${row.user_status}">
164                  <i class="fas fa-user-lock text-danger"></i>
165                  </span>`;
166           } else if (row.user_status === this.userExpired) {
167             return `<span class="icon-label" title="${row.user_status}">
168                  <i class="fas fa-user-times text-warning"></i>
169                  </span>`;
170           } else if (row.user_status === this.userAlwaysActive) {
171             return `<span class="icon-label" title="${row.user_status}">
172                  <i class="fas fa-user-shield text-info"></i>
173                  </span>`;
174           } else {
175             return `<span>${row.user_status}</span>`;
176           }
177         }
178       },
179       account_expire_time: { title: this.translateService.instant('Expires in'), width: '10%' },
180       modified: { title: this.translateService.instant('MODIFIED'), width: '10%' },
181       created: { title: this.translateService.instant('CREATED'), width: '10%' },
182       Actions: {
183         name: 'Action', width: '5%', filter: false, sort: false, title: this.translateService.instant('ACTIONS'), type: 'custom',
184         valuePrepareFunction: (cell: UserData, row: UserData): UserData => row,
185         renderComponent: UsersActionComponent
186       }
187     };
188   }
189
190   /** smart table Data Settings @public */
191   public generateSettings(): void {
192     this.settings = {
193       edit: { editButtonContent: '<i class="fa fa-edit" title="Edit"></i>', confirmSave: true },
194       delete: { deleteButtonContent: '<i class="far fa-trash-alt" title="delete"></i>', confirmDelete: true },
195       columns: this.columnLists,
196       actions: { add: false, edit: false, delete: false, position: 'right' },
197       attr: this.sharedService.tableClassConfig(),
198       pager: this.sharedService.paginationPagerConfig(),
199       noDataMessage: this.translateService.instant('NODATAMSG')
200     };
201   }
202
203   /** To hide coulmns in smart table @public */
204   public hideColumnForUser(): void {
205     if (!this.isAdminShow) {
206       const userStatus: string = 'user_status';
207       const expire: string = 'account_expire_time';
208       // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
209       delete this.columnLists[userStatus];
210       // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
211       delete this.columnLists[expire];
212     } else {
213       const modified: string = 'modified';
214       // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
215       delete this.columnLists[modified];
216     }
217   }
218
219   /** on Navigate to Composer Page @public */
220   public composeUser(): void {
221     // eslint-disable-next-line security/detect-non-literal-fs-filename
222     const modalRef: NgbModalRef = this.modalService.open(AddEditUserComponent, { backdrop: 'static' });
223     modalRef.componentInstance.userTitle = this.translateService.instant('PAGE.USERS.NEWUSER');
224     modalRef.componentInstance.userType = 'add';
225     modalRef.result.then((result: MODALCLOSERESPONSEDATA) => {
226       if (result) {
227         this.sharedService.callData();
228       }
229     }).catch((): void => {
230       // Catch Navigation Error
231     });
232   }
233
234   /** smart table listing manipulation @private */
235   public onChange(perPageValue: number): void {
236     this.dataSource.setPaging(1, perPageValue, true);
237   }
238
239   /** OnUserRowSelect function @private */
240   public onUserRowSelect(event: MessageEvent): void {
241     Object.assign(event.data, { page: 'users' });
242     this.dataService.changeMessage(event.data);
243   }
244
245   /** Set up user details @public */
246   public setUserDetails(userData: UserDetail): void {
247     const userDataObj: UserData = {
248       username: userData.username,
249       modified: this.sharedService.convertEpochTime(!isNullOrUndefined(userData._admin) ? userData._admin.modified : null),
250       created: this.sharedService.convertEpochTime(!isNullOrUndefined(userData._admin) ? userData._admin.created : null),
251       projects: userData.projectListName,
252       identifier: userData._id,
253       user_status: userData._admin.user_status,
254       account_expire_time: (!isNullOrUndefined(userData._admin) && !isNullOrUndefined(userData._admin.account_expire_time)) ? this.sharedService.convertEpochTime(
255         userData._admin.account_expire_time) : 'N/A'
256     };
257     this.userData.push(userDataObj);
258   }
259
260   /**
261    * Lifecyle hook which get trigger on component destruction
262    */
263   public ngOnDestroy(): void {
264     this.generateDataSub.unsubscribe();
265   }
266
267   /** Fetching the data from server to Load in the smarttable @protected */
268   protected generateData(): void {
269     this.isLoadingResults = true;
270     this.restService.getResource(environment.USERS_URL).subscribe((usersData: UserDetail[]) => {
271       this.userData = [];
272       usersData.forEach((userData: UserDetail) => {
273         if (userData.projects.length > 0) {
274           userData.projectListName = userData.projects.join(', ');
275         } else {
276           userData.projectListName = '';
277         }
278         this.setUserDetails(userData);
279       });
280       if (this.userData.length > 0) {
281         this.checkDataClass = 'dataTables_present';
282       } else {
283         this.checkDataClass = 'dataTables_empty';
284       }
285       this.dataSource.load(this.userData).then((data: {}) => {
286         this.isLoadingResults = false;
287       }).catch((): void => {
288         // Catch Navigation Error
289       });
290     }, (error: ERRORDATA) => {
291       this.restService.handleError(error, 'get');
292       this.isLoadingResults = false;
293     });
294   }
295 }