group.component.ts 15.5 KB
Newer Older
1
2
3
4
import { Component, OnInit, ViewChild } from '@angular/core';
import { SignaturesContentService } from '../../service/signatures.service';
import { NotificationService } from '../../service/notification.service';
import { HttpClient } from '@angular/common/http';
5
6
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
7
import { MatSort, Sort } from '@angular/material/sort';
8
import { map, finalize, tap, catchError } from 'rxjs/operators';
9
10
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
11
import { AuthService } from '../../service/auth.service';
12
13
import { AlertController, ModalController, PopoverController } from '@ionic/angular';
import { UsersComponent } from './list/users.component';
14
import { of } from 'rxjs';
15
import { GroupModalComponent } from './modal/group-modal.component';
16
import { FunctionsService } from '../../service/functions.service';
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


export interface Group {
    id: string;
    label: string;
    users: any[];
    privileges: any[];
}

@Component({
    selector: 'app-administration-group',
    templateUrl: 'group.component.html',
    styleUrls: ['../administration.scss', 'group.component.scss'],
})

export class GroupComponent implements OnInit {

34
35
36
    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

37
38
39
40
41
42
43
    creationMode: boolean = true;
    loading: boolean = true;
    group: Group;
    groupClone: Group;
    title: string = '';
    displayedColumns: string[];
    usersList: any[];
44
    sortedData: any[];
45
    groups: any[] = [];
46
    allGroups: any[] = [];
47

48
49
50
51
52
53
54
55
56
57
58
    constructor(
        public http: HttpClient,
        private translate: TranslateService,
        private route: ActivatedRoute,
        private router: Router,
        public signaturesService: SignaturesContentService,
        public notificationService: NotificationService,
        public dialog: MatDialog,
        public authService: AuthService,
        public popoverController: PopoverController,
        public modalController: ModalController,
59
60
        public alertController: AlertController,
        public functions: FunctionsService
61
    ) {
62
63
64
65
66
67
68
        this.displayedColumns = ['firstname', 'lastname', 'actions'];
        this.group = {
            id: '',
            label: '',
            users: [],
            privileges: []
        };
69
        this.groupClone = JSON.parse(JSON.stringify(this.group));
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    }

    ngOnInit(): void {
        this.route.params.subscribe((params: any) => {
            if (params['id'] === undefined) {
                this.creationMode = true;
                this.title = this.translate.instant('lang.groupCreation');
                this.loading = false;
                this.groupClone = JSON.parse(JSON.stringify(this.group));
            } else {
                this.creationMode = false;
                this.usersList = [];

                this.http.get('../rest/groups/' + params['id'])
                    .pipe(
                        map((data: any) => data.group),
86
87
                        finalize(() => {
                            this.loading = false;
88
89
                        }),
                        tap((data: any) => {
90
91
92
93
                            this.group = data;
                            this.groupClone = JSON.parse(JSON.stringify(this.group));
                            this.title = this.group.label;
                            this.updateDataTable();
94
95
96
                            if (this.group.privileges.find((privilige: any) => privilige.id === 'manage_users') !== undefined) {
                                this.getGroups();
                            }
97
98
99
100
                        }),
                        catchError((err: any) => {
                            this.notificationService.handleErrors(err);
                            return of(false);
101
102
103
                        })
                    )
                    .subscribe();
104

105
                this.http.get('../rest/users?mode=all')
106
                    .pipe(
107
108
                        map((data: any) => data.users),
                        tap((data: any) => {
109
                            this.usersList = data;
110
111
112
113
114
115
116
                        }),
                        catchError((err: any) => {
                            this.notificationService.handleErrors(err);
                            return of(false);
                        })
                    )
                    .subscribe();
117
118
119
120
121
            }
        });
    }

    updateDataTable() {
122
123
124
        this.sortedData = this.group.users.slice();
    }

125
    async openUserList() {
126
127
128
129
130
131
132
133
134
135
136
        const modal = await this.modalController.create({
            component: UsersComponent,
            componentProps: {
                'users': this.group.users
            }
        });
        await modal.present();
        const { data } = await modal.onWillDismiss();
        if (data !== undefined) {
            this.linkUser(data);
        }
137
138
    }

139
    async openGroupList() {
140
        await this.getPrivilegeParameters();
141
142
143
144
145
146
147
148
149
150
        const modal = await this.modalController.create({
            component: GroupModalComponent,
            componentProps: {
                groups: this.groups
            }
        });
        await modal.present();
        const { data } = await modal.onWillDismiss();
        if (data !== undefined) {
            this.groups = data;
151
152
            const privilege: any = this.group.privileges.find((item: any) => item.id === 'manage_users');
            this.updatePrivilege(privilege);
153
154
155
        }
    }

156
157
    getPrivilegeParameters() {
        const privilege: any = this.group.privileges.find((item: any) => item.id === 'manage_users');
158
        return new Promise((resolve) => {
159
            this.http.get('../rest/groups/' + this.group.id + '/privilege/' + privilege.id).pipe(
160
                tap((data: any) => {
161
162
163
164
165
166
167
168
169
170
171
                    this.allGroups.forEach((element: any, index: number) => {
                        if (this.groups.find((item: any) => item.id === element.id) === undefined) {
                            let checked: boolean;
                            if (data.parameters.authorized !== undefined) {
                                if (data.parameters.authorized.indexOf(element.id) > -1) {
                                    checked = true;
                                } else {
                                    checked = false;
                                }
                            } else {
                                checked = true;
172
                            }
173
174
175
176
177
178
179
180
181
182
                            this.groups.push(
                                {
                                    id: element.id,
                                    label: element.label,
                                    checked:  checked
                                }
                            );
                        }
                    });
                    this.groups = [...new Set(this.groups)];
183
184
185
186
187
188
189
190
191
192
193
194
195
196
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getChecked() {
        return this.groups.filter((item: any) => item.checked).length;
    }

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    canValidate() {
        if (this.group.label === this.groupClone.label) {
            return false;
        } else {
            return true;
        }
    }

    onSubmit() {
        if (this.creationMode) {
            this.createGroup();
        } else {
            this.modifyGroup();
        }
    }

    linkUser(user: any) {
        this.http.put('../rest/groups/' + this.group.id + '/users', { userId: user.id })
215
216
            .pipe(
                tap(() => {
217
218
219
                    this.group.users.push(user);
                    this.updateDataTable();
                    this.notificationService.success('lang.userAdded');
220
221
222
223
224
225
226
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
227
228
    }

229
    async unlinkUser(userToDelete: any) {
230
        if (userToDelete.id === this.authService.user.id) {
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
            const alert = await this.alertController.create({
                // cssClass: 'custom-alert-danger',
                header: this.translate.instant('lang.confirmMsg'),
                buttons: [
                    {
                        text: this.translate.instant('lang.no'),
                        role: 'cancel',
                        cssClass: 'secondary',
                        handler: () => { }
                    },
                    {
                        text: this.translate.instant('lang.yes'),
                        handler: () => {
                            this.deleteUser(userToDelete);
                        }
                    }
                ]
248
            });
249
250
251

            await alert.present();

252
253
254
255
256
257
258
259
        } else {
            this.deleteUser(userToDelete);
        }
    }


    deleteUser(userToDelete: any) {
        this.http.delete('../rest/groups/' + this.group.id + '/users/' + userToDelete.id, {})
260
261
            .pipe(
                tap(() => {
262
263
264
265
                    const indexToDelete = this.group.users.findIndex((user: any) => user.id === userToDelete.id);
                    this.group.users.splice(indexToDelete, 1);
                    this.updateDataTable();
                    this.notificationService.success('lang.userDeleted');
266
267
268
269
270
271
272
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
273
274
275
276
277
    }

    modifyGroup() {
        this.loading = true;
        this.http.put('../rest/groups/' + this.group.id, this.group)
278
279
            .pipe(
                tap(() => {
280
281
                    this.router.navigate(['/administration/groups']);
                    this.notificationService.success('lang.groupUpdated');
282
283
284
285
286
287
288
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
289
290
291
292
293
    }

    createGroup() {
        this.loading = true;
        this.http.post('../rest/groups', this.group)
294
295
            .pipe(
                tap((data: any) => {
296
                    this.router.navigate(['/administration/groups/' + data.id]);
297
                    this.notificationService.success('lang.groupAdded');
298
299
300
301
302
303
304
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
305
306
    }

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
    async deleteGroup() {
        const alert = await this.alertController.create({
            // cssClass: 'custom-alert-danger',
            header: this.translate.instant('lang.confirmMsg'),
            buttons: [
                {
                    text: this.translate.instant('lang.no'),
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => { }
                },
                {
                    text: this.translate.instant('lang.yes'),
                    handler: () => {
                        this.http.delete('../rest/groups/' + this.group.id)
322
323
                            .pipe(
                                tap(() => {
324
325
                                    this.router.navigate(['/administration/groups']);
                                    this.notificationService.success('lang.groupDeleted');
326
327
328
329
330
331
332
                                }),
                                catchError((err: any) => {
                                    this.notificationService.handleErrors(err);
                                    return of(false);
                                })
                            )
                            .subscribe();
333
334
335
                    }
                }
            ]
336
        });
337
338

        await alert.present();
339
340
    }

341
    async togglePrivilege(privilege: any, toggle: boolean) {
342
        if (privilege.id === 'manage_groups' && privilege.checked) {
343
344
345
            if (!toggle) {
                privilege.checked = !privilege.checked;
            }
346
347
348
349
350
351
352
353
            const alert = await this.alertController.create({
                header: this.translate.instant('lang.confirmMsg'),
                message: this.translate.instant('lang.groupWarnMsg'),
                buttons: [
                    {
                        text: this.translate.instant('lang.no'),
                        role: 'cancel',
                        cssClass: 'secondary',
354
355
356
                        handler: () => {
                            privilege.checked = !privilege.checked;
                        }
357
358
359
360
361
362
363
364
                    },
                    {
                        text: this.translate.instant('lang.yes'),
                        handler: () => {
                            this.updatePrivilege(privilege);
                        }
                    }
                ]
365
            });
366
            await alert.present();
367
        } else {
368
369
370
371
372
373
            if (privilege.id === 'manage_users') {
                if (!privilege.checked) {
                    this.getGroups();
                } else {
                    this.groups = [];
                }
374
            }
375
376
377
            if (!toggle) {
                privilege.checked = !privilege.checked;
            }
378
379
380
            setTimeout(() => {
                this.updatePrivilege(privilege);
            }, 200);
381
382
383
        }
    }

384
385
386
387
388
389
390
391
392
393
394
395
    getGroups() {
        this.http.get('../rest/groups').pipe(
            tap((data: any) => {
                this.allGroups = data.groups;
            }),
            catchError((err: any) => {
                this.notificationService.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }

396
    updatePrivilege(privilege: any) {
397
        const objTosend: any = {
398
399
            checked: privilege.checked,
            parameters: {
400
                authorized: this.groups.filter((element: any) => element.checked).map((item: any) => item.id)
401
            }
402
        };
403
404
        if (privilege.id !== 'manage_users') {
            delete objTosend.parameters.authorized;
405
406
        }
        this.http.put('../rest/groups/' + this.group.id + '/privilege/' + privilege.id, objTosend)
407
408
            .pipe(
                tap(() => {
409
                    this.notificationService.success('lang.privilegeUpdated');
410
                    this.authService.updateUserInfoWithTokenRefresh();
411
412
413
414
415
416
417
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
418
419
420
421
422
423
    }

    cancel() {
        this.router.navigate(['/administration/groups']);
    }

424
425
426
427
428
    sortData(sort: Sort) {
        const data = this.group.users.slice();
        if (!sort.active || sort.direction === '') {
            this.sortedData = data;
            return;
429
        }
430
431
432
433
434

        this.sortedData = data.sort((a, b) => {
            const isAsc = sort.direction === 'asc';
            return compare(a[sort.active], b[sort.active], isAsc);
        });
435
    }
436
437
438
439

    canManage(privilege: any) {
        return privilege.id === 'manage_users' && privilege.checked && this.group.users.find((user: any) => user.id === this.authService.user.id) !== undefined;
    }
440
}
441
442
443
444

function compare(a: number | string, b: number | string, isAsc: boolean) {
    return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}