Skip to content
Snippets Groups Projects
group.component.ts 15.8 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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';
    
    import { MatDialog } from '@angular/material/dialog';
    import { MatPaginator } from '@angular/material/paginator';
    
    import { MatSort, Sort } from '@angular/material/sort';
    
    import { map, finalize, tap, catchError } from 'rxjs/operators';
    
    import { ActivatedRoute, Router } from '@angular/router';
    import { TranslateService } from '@ngx-translate/core';
    
    import { AuthService } from '../../service/auth.service';
    
    import { AlertController, ModalController, PopoverController } from '@ionic/angular';
    import { UsersComponent } from './list/users.component';
    
    import { GroupModalComponent } from './modal/group-modal.component';
    
    import { FunctionsService } from '../../service/functions.service';
    
    
    
    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 {
    
    
        @ViewChild(MatPaginator) paginator: MatPaginator;
        @ViewChild(MatSort) sort: MatSort;
    
    
        creationMode: boolean = true;
        loading: boolean = true;
        group: Group;
        groupClone: Group;
        title: string = '';
        displayedColumns: string[];
        usersList: any[];
    
        sortedData: any[];
    
        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,
    
            public alertController: AlertController,
            public functions: FunctionsService
    
            this.displayedColumns = ['firstname', 'lastname', 'actions'];
            this.group = {
                id: '',
                label: '',
                users: [],
                privileges: []
            };
    
            this.groupClone = JSON.parse(JSON.stringify(this.group));
    
        }
    
        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),
    
                            finalize(() => {
                                this.loading = false;
    
                                this.group = data;
                                this.groupClone = JSON.parse(JSON.stringify(this.group));
                                this.title = this.group.label;
                                this.updateDataTable();
    
                                if (this.group.privileges.find((privilige: any) => privilige.id === 'manage_users') !== undefined) {
                                    this.getGroups();
                                }
    
                            }),
                            catchError((err: any) => {
                                this.notificationService.handleErrors(err);
                                return of(false);
    
                    this.http.get('../rest/users?mode=all')
    
                            map((data: any) => data.users),
                            tap((data: any) => {
    
                            }),
                            catchError((err: any) => {
                                this.notificationService.handleErrors(err);
                                return of(false);
                            })
                        )
                        .subscribe();
    
            this.sortedData = this.group.users.slice();
        }
    
    
            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);
            }
    
            const modal = await this.modalController.create({
                component: GroupModalComponent,
                componentProps: {
    
                    groups: this.groups,
                    editUser: false
    
                }
            });
            await modal.present();
            const { data } = await modal.onWillDismiss();
            if (data !== undefined) {
                this.groups = data;
    
                const privilege: any = this.group.privileges.find((item: any) => item.id === 'manage_users');
    
                this.http.get('../rest/groups/' + this.group.id).pipe(
    
                        const manageUsers: any = data.group.privileges.find((item: any) => item.id === 'manage_users');
                        if (!this.functions.empty(manageUsers)) {
                            this.allGroups.forEach((element: any, index: number) => {
                                if (this.groups.find((item: any) => item.id === element.id) === undefined) {
                                    let checked: boolean;
                                    if (!this.functions.empty(manageUsers.parameters.authorized)) {
                                        checked = manageUsers.parameters.authorized.indexOf(element.id) > -1;
    
                                    this.groups.push(
                                        {
                                            id: element.id,
                                            label: element.label,
                                            checked:  checked
                                        }
                                    );
    
                            });
                            this.groups = [...new Set(this.groups)];
                        }
    
                        resolve(true);
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                ).subscribe();
            });
        }
    
        getChecked() {
            return this.groups.filter((item: any) => item.checked).length;
        }
    
    
        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 })
    
                        this.group.users.push(user);
                        this.updateDataTable();
                        this.notificationService.success('lang.userAdded');
    
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                )
                .subscribe();
    
        async unlinkUser(userToDelete: any) {
    
            if (userToDelete.id === this.authService.user.id) {
    
                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);
                            }
                        }
                    ]
    
    
                await alert.present();
    
    
            } else {
                this.deleteUser(userToDelete);
            }
        }
    
    
        deleteUser(userToDelete: any) {
            this.http.delete('../rest/groups/' + this.group.id + '/users/' + userToDelete.id, {})
    
                        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');
    
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                )
                .subscribe();
    
        }
    
        modifyGroup() {
            this.loading = true;
            this.http.put('../rest/groups/' + this.group.id, this.group)
    
                        this.router.navigate(['/administration/groups']);
                        this.notificationService.success('lang.groupUpdated');
    
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                )
                .subscribe();
    
        }
    
        createGroup() {
            this.loading = true;
            this.http.post('../rest/groups', this.group)
    
                        this.router.navigate(['/administration/groups/' + data.id]);
    
                        this.notificationService.success('lang.groupAdded');
    
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                )
                .subscribe();
    
        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)
    
                                        this.router.navigate(['/administration/groups']);
                                        this.notificationService.success('lang.groupDeleted');
    
                                    }),
                                    catchError((err: any) => {
                                        this.notificationService.handleErrors(err);
                                        return of(false);
                                    })
                                )
                                .subscribe();
    
    
            await alert.present();
    
        async togglePrivilege(privilege: any, toggle: boolean) {
    
            if (privilege.id === 'manage_groups' && privilege.checked) {
    
                if (!toggle) {
                    privilege.checked = !privilege.checked;
                }
    
                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',
    
                            handler: () => {
                                privilege.checked = !privilege.checked;
                            }
    
                        },
                        {
                            text: this.translate.instant('lang.yes'),
                            handler: () => {
                                this.updatePrivilege(privilege);
                            }
                        }
                    ]
    
                await alert.present();
    
                if (privilege.id === 'manage_users') {
                    if (!privilege.checked) {
                        this.getGroups();
                    } else {
                        this.groups = [];
                    }
    
                if (!toggle) {
                    privilege.checked = !privilege.checked;
                }
    
                setTimeout(() => {
                    this.updatePrivilege(privilege);
                }, 200);
    
        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();
        }
    
    
            if (!this.dataChanged && this.groups.length === 0 && privilege.checked) {
                this.groups = this.allGroups.map((group: any) => ({
                    id: group.id,
                    label: group.label,
                    checked: true
                }));
            }
    
    
                checked: privilege.checked,
                parameters: {
    
                    authorized: this.groups.filter((element: any) => element.checked).map((item: any) => item.id)
    
            if (privilege.id !== 'manage_users') {
                delete objTosend.parameters.authorized;
    
            }
            this.http.put('../rest/groups/' + this.group.id + '/privilege/' + privilege.id, objTosend)
    
                        this.notificationService.success('lang.privilegeUpdated');
    
                        this.authService.updateUserInfoWithTokenRefresh();
    
                    }),
                    catchError((err: any) => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                )
                .subscribe();
    
        sortData(sort: Sort) {
            const data = this.group.users.slice();
            if (!sort.active || sort.direction === '') {
                this.sortedData = data;
                return;
    
    
            this.sortedData = data.sort((a, b) => {
                const isAsc = sort.direction === 'asc';
                return compare(a[sort.active], b[sort.active], isAsc);
            });
    
    
        canManage(privilege: any) {
    
            return privilege.id === 'manage_users' && privilege.checked;
    
    
    function compare(a: number | string, b: number | string, isAsc: boolean) {
        return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
    }