group.component.ts 15.8 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
    dataChanged: boolean = false;

50
51
52
53
54
55
56
57
58
59
60
    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,
61
62
        public alertController: AlertController,
        public functions: FunctionsService
63
    ) {
64
65
66
67
68
69
70
        this.displayedColumns = ['firstname', 'lastname', 'actions'];
        this.group = {
            id: '',
            label: '',
            users: [],
            privileges: []
        };
71
        this.groupClone = JSON.parse(JSON.stringify(this.group));
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    }

    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),
88
89
                        finalize(() => {
                            this.loading = false;
90
91
                        }),
                        tap((data: any) => {
92
93
94
95
                            this.group = data;
                            this.groupClone = JSON.parse(JSON.stringify(this.group));
                            this.title = this.group.label;
                            this.updateDataTable();
96
97
98
                            if (this.group.privileges.find((privilige: any) => privilige.id === 'manage_users') !== undefined) {
                                this.getGroups();
                            }
99
100
101
102
                        }),
                        catchError((err: any) => {
                            this.notificationService.handleErrors(err);
                            return of(false);
103
104
105
                        })
                    )
                    .subscribe();
106

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

    updateDataTable() {
124
125
126
        this.sortedData = this.group.users.slice();
    }

127
    async openUserList() {
128
129
130
131
132
133
134
135
136
137
138
        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);
        }
139
140
    }

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

160
161
    getPrivilegeParameters() {
        const privilege: any = this.group.privileges.find((item: any) => item.id === 'manage_users');
162
        return new Promise((resolve) => {
163
            this.http.get('../rest/groups/' + this.group.id + '/privilege/' + privilege.id).pipe(
164
                tap((data: any) => {
165
166
167
168
169
170
171
172
173
174
175
                    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;
176
                            }
177
178
179
180
181
182
183
184
185
186
                            this.groups.push(
                                {
                                    id: element.id,
                                    label: element.label,
                                    checked:  checked
                                }
                            );
                        }
                    });
                    this.groups = [...new Set(this.groups)];
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

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

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    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 })
219
220
            .pipe(
                tap(() => {
221
222
223
                    this.group.users.push(user);
                    this.updateDataTable();
                    this.notificationService.success('lang.userAdded');
224
225
226
227
228
229
230
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
231
232
    }

233
    async unlinkUser(userToDelete: any) {
234
        if (userToDelete.id === this.authService.user.id) {
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
            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);
                        }
                    }
                ]
252
            });
253
254
255

            await alert.present();

256
257
258
259
260
261
262
263
        } else {
            this.deleteUser(userToDelete);
        }
    }


    deleteUser(userToDelete: any) {
        this.http.delete('../rest/groups/' + this.group.id + '/users/' + userToDelete.id, {})
264
265
            .pipe(
                tap(() => {
266
267
268
269
                    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');
270
271
272
273
274
275
276
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
277
278
279
280
281
    }

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

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

311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    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)
326
327
                            .pipe(
                                tap(() => {
328
329
                                    this.router.navigate(['/administration/groups']);
                                    this.notificationService.success('lang.groupDeleted');
330
331
332
333
334
335
336
                                }),
                                catchError((err: any) => {
                                    this.notificationService.handleErrors(err);
                                    return of(false);
                                })
                            )
                            .subscribe();
337
338
339
                    }
                }
            ]
340
        });
341
342

        await alert.present();
343
344
    }

345
    async togglePrivilege(privilege: any, toggle: boolean) {
346
        if (privilege.id === 'manage_groups' && privilege.checked) {
347
348
349
            if (!toggle) {
                privilege.checked = !privilege.checked;
            }
350
351
352
353
354
355
356
357
            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',
358
359
360
                        handler: () => {
                            privilege.checked = !privilege.checked;
                        }
361
362
363
364
365
366
367
368
                    },
                    {
                        text: this.translate.instant('lang.yes'),
                        handler: () => {
                            this.updatePrivilege(privilege);
                        }
                    }
                ]
369
            });
370
            await alert.present();
371
        } else {
372
373
374
375
376
377
            if (privilege.id === 'manage_users') {
                if (!privilege.checked) {
                    this.getGroups();
                } else {
                    this.groups = [];
                }
378
            }
379
380
381
            if (!toggle) {
                privilege.checked = !privilege.checked;
            }
382
383
384
            setTimeout(() => {
                this.updatePrivilege(privilege);
            }, 200);
385
386
387
        }
    }

388
389
390
391
392
393
394
395
396
397
398
399
    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();
    }

400
    updatePrivilege(privilege: any) {
401
402
403
404
405
406
407
408
        if (!this.dataChanged && this.groups.length === 0 && privilege.checked) {
            this.groups = this.allGroups.map((group: any) => ({
                id: group.id,
                label: group.label,
                checked: true
            }));
        }

409
        const objTosend: any = {
410
411
            checked: privilege.checked,
            parameters: {
412
                authorized: this.groups.filter((element: any) => element.checked).map((item: any) => item.id)
413
            }
414
        };
415
416
        if (privilege.id !== 'manage_users') {
            delete objTosend.parameters.authorized;
417
418
        }
        this.http.put('../rest/groups/' + this.group.id + '/privilege/' + privilege.id, objTosend)
419
420
            .pipe(
                tap(() => {
421
                    this.notificationService.success('lang.privilegeUpdated');
422
                    this.authService.updateUserInfoWithTokenRefresh();
423
424
425
426
427
428
429
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            )
            .subscribe();
430
431
432
433
434
435
    }

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

436
437
438
439
440
    sortData(sort: Sort) {
        const data = this.group.users.slice();
        if (!sort.active || sort.direction === '') {
            this.sortedData = data;
            return;
441
        }
442
443
444
445
446

        this.sortedData = data.sort((a, b) => {
            const isAsc = sort.direction === 'asc';
            return compare(a[sort.active], b[sort.active], isAsc);
        });
447
    }
448
449

    canManage(privilege: any) {
450
        return privilege.id === 'manage_users' && privilege.checked;
451
    }
452
}
453
454
455
456

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