Skip to content
Snippets Groups Projects
visa-workflow.component.ts 12 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Component, Input, OnInit, ViewChild } from '@angular/core';
    
    import { SignaturesContentService } from '../../service/signatures.service';
    
    import { HttpClient } from '@angular/common/http';
    
    import { AuthService } from '../../service/auth.service';
    
    import { catchError, tap } from 'rxjs/operators';
    import { of } from 'rxjs';
    import { NotificationService } from '../../service/notification.service';
    
    import { AlertController, IonReorderGroup, ModalController, PopoverController } from '@ionic/angular';
    
    import { ItemReorderEventDetail } from '@ionic/core';
    
    import { TranslateService } from '@ngx-translate/core';
    import { OtpCreateComponent } from './otps/otp-create.component';
    
    import { OtpService } from './otps/otp.service';
    
    
    @Component({
        selector: 'app-visa-workflow',
        templateUrl: 'visa-workflow.component.html',
        styleUrls: ['visa-workflow.component.scss'],
    })
    export class VisaWorkflowComponent implements OnInit {
    
    
        @Input() editMode: boolean = false;
        @Input() visaWorkflow: any = [];
        @ViewChild(IonReorderGroup) reorderGroup: IonReorderGroup;
    
    
        loading: boolean = false;
    
    
        visaUsersSearchVal: string = '';
        visaUsersList: any = [];
        showVisaUsersList: boolean = false;
    
        customPopoverOptions = {
            header: 'Roles'
        };
    
        visaWorkflowModels: any[] = [];
    
        constructor(
            public http: HttpClient,
    
            private translate: TranslateService,
            public alertController: AlertController,
    
            public signaturesService: SignaturesContentService,
    
            public authService: AuthService,
            public notificationService: NotificationService,
    
            public modalController: ModalController,
    
            private otpService: OtpService,
    
        ngOnInit(): void {
    
            this.visaWorkflow.forEach((element: any, index: number) => {
                this.getAvatarUser(index);
    
        doReorder(ev: CustomEvent<ItemReorderEventDetail>) {
    
            if (this.canMoveUser(ev)) {
                this.visaWorkflow = ev.detail.complete(this.visaWorkflow);
            } else {
                this.notificationService.error('lang.errorUserSignType');
                ev.detail.complete(false);
            }
        }
    
        canMoveUser(ev: CustomEvent<ItemReorderEventDetail>) {
            const newWorkflow = this.array_move(this.visaWorkflow.slice(), ev.detail.from, ev.detail.to);
            const res = this.isValidWorkflow(newWorkflow);
            return res;
        }
    
        isValidWorkflow(workflow: any = this.visaWorkflow) {
            let res: boolean = true;
            workflow.forEach((item: any, indexUserRgs: number) => {
                if (['visa', 'stamp'].indexOf(item.role) === -1) {
                    if (workflow.filter((itemUserStamp: any, indexUserStamp: number) => indexUserStamp > indexUserRgs && itemUserStamp.role === 'stamp').length > 0) {
                        res = false;
                    }
                }
            });
            return res;
    
        array_move(arr: any, old_index: number, new_index: number) {
            if (new_index >= arr.length) {
                let k = new_index - arr.length + 1;
                while (k--) {
                    arr.push(undefined);
                }
            }
            arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
            return arr; // for testing
    
        getVisaUsers(ev: any) {
            this.showVisaUsersList = true;
            if (ev.detail.value === '') {
                this.resetVisaUsersList();
            } else if (ev.detail.value.length >= 3) {
                this.http.get('../rest/autocomplete/users?search=' + ev.detail.value).pipe(
                    tap((res: any) => {
                        this.visaUsersList = res;
                    }),
                    catchError(err => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                ).subscribe();
            }
        }
    
        addUser(user: any, searchInput: any) {
            this.resetVisaUsersList();
    
    
            user.signatureModes.unshift('visa');
    
    
            const userObj: any = {
                'userId': user.id,
                'userDisplay': `${user.firstname} ${user.lastname}`,
    
                'role': user.signatureModes[user.signatureModes.length - 1],
    
                'processDate': null,
                'current': false,
    
                'modes': user.signatureModes
    
            };
            this.visaWorkflow.push(userObj);
    
            if (!this.isValidWorkflow()) {
                this.visaWorkflow[this.visaWorkflow.length - 1].role = 'visa';
            }
    
            this.getAvatarUser(this.visaWorkflow.length - 1);
            this.visaUsersSearchVal = '';
            searchInput.setFocus();
        }
    
        removeUser(index: number) {
            this.visaWorkflow.splice(index, 1);
        }
    
    
        async getAvatarUser(index: number) {
            if (this.visaWorkflow[index].userId === null) {
                this.visaWorkflow[index].userPicture = await this.otpService.getUserOtpIcon('yousign');
            } else if (this.visaWorkflow[index].userPicture === undefined && this.visaWorkflow[index].userDisplay !== '') {
    
                this.http.get('../rest/users/' + this.visaWorkflow[index].userId + '/picture').pipe(
                    tap((data: any) => {
    
                        this.visaWorkflow[index].userPicture = data.picture;
    
                    }),
                    catchError(err => {
                        this.notificationService.handleErrors(err);
                        return of(false);
                    })
                ).subscribe();
            }
    
        }
    
        resetVisaUsersList() {
            this.visaUsersList = [];
        }
    
        async openOtpModal(ev: any) {
            const modal = await this.modalController.create({
    
                cssClass: 'custom-modal',
    
                component: OtpCreateComponent,
                backdropDismiss: false,
    
            await modal.present();
    
            modal.onDidDismiss()
    
                .then(async (result: any) => {
    
                    if (typeof result.data === 'object') {
                        const obj: any = {
                            'userId': null,
                            'userDisplay': `${result.data.firstname} ${result.data.lastname}`,
    
                            'userPicture': await this.otpService.getUserOtpIcon(result.data.type),
    
                            'role': result.data.role,
                            'processDate': null,
                            'current': false,
    
                            'modes': [result.data.role],
                            'otp': result.data
    
                        };
                        this.visaWorkflow.push(obj);
    
        }
    
        getCurrentWorkflow() {
            return this.visaWorkflow;
        }
    
    
        getRole(id: string) {
    
            return this.authService.signatureRoles.filter((mode: any) => mode.id === id)[0];
    
    
        loadWorkflow(workflow: any) {
            this.visaWorkflow = workflow;
    
            const length = this.visaWorkflow.length;
            for (let index = 0; index < length; index++) {
    
    
        isValidRole(indexWorkflow: any, role: string, currentRole: string) {
            if (this.visaWorkflow.filter((item: any, index: any) => index > indexWorkflow && ['stamp'].indexOf(item.role) > -1).length > 0 && ['visa', 'stamp'].indexOf(currentRole) > -1 && ['visa', 'stamp'].indexOf(role) === -1) {
                return false;
            } else if (this.visaWorkflow.filter((item: any, index: any) => index < indexWorkflow && ['visa', 'stamp'].indexOf(item.role) === -1).length > 0 && role === 'stamp') {
                return false;
            } else {
                return true;
            }
        }
    
    
        async createModel() {
            const alert = await this.alertController.create({
                header: this.translate.instant('lang.newTemplate'),
                message: this.translate.instant('lang.newTemplateDesc'),
                inputs: [
                    {
                        name: 'title',
                        type: 'text',
                        placeholder: this.translate.instant('lang.label') + ' *',
                    },
                ],
                buttons: [
                    {
                        text: this.translate.instant('lang.cancel'),
                        role: 'cancel',
                        handler: () => { }
                    }, {
                        text: this.translate.instant('lang.validate'),
                        handler: (data: any) => {
                            if (data.title !== '') {
                                this.saveModel(data.title);
                                return true;
                            } else {
                                this.notificationService.error(this.translate.instant('lang.label') + ' ' + this.translate.instant('lang.mandatory'));
                                return false;
                            }
                        }
                    }
                ]
            });
    
            await alert.present();
        }
    
        saveModel(title: string) {
            const objToSend: any = {
                title: title,
                items: this.visaWorkflow.map((item: any) => ({
                    userId: item.userId,
                    mode: this.authService.getWorkflowMode(item.role),
                    signatureMode: this.authService.getSignatureMode(item.role)
                }))
            };
            this.http.post('../rest/workflowTemplates', objToSend).pipe(
                tap((res: any) => {
                    this.notificationService.success('lang.modelCreated');
                    this.visaWorkflowModels.push({ id: res.id, title: title });
                }),
                catchError(err => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        }
    
        async removeModel(model: any) {
            const alert = await this.alertController.create({
                header: this.translate.instant('lang.delete'),
                message: this.translate.instant('lang.deleteTemplate'),
                buttons: [
                    {
                        text: this.translate.instant('lang.no'),
                        role: 'cancel',
                        handler: () => { }
                    }, {
                        text: this.translate.instant('lang.yes'),
                        handler: () => {
                            this.http.delete(`../rest/workflowTemplates/${model.id}`).pipe(
                                tap(() => {
                                    this.visaWorkflowModels = this.visaWorkflowModels.filter((item: any) => item.id !== model.id);
                                    this.notificationService.success(`Modèle ${model.title} supprimé`);
                                }),
                                catchError(err => {
                                    this.notificationService.handleErrors(err);
                                    return of(false);
                                })
                            ).subscribe();
                        }
                    }
                ]
            });
    
            await alert.present();
        }
    
        loadVisaWorkflow(model: any) {
            this.http.get(`../rest/workflowTemplates/${model.id}`).pipe(
                tap((data: any) => {
                    const workflows: any[] = data.workflowTemplate.items.map((item: any) => {
    
                        const obj: any = {
                            'userId': item.userId,
                            'userDisplay': item.userLabel,
                            'role': item.mode === 'visa' ? 'visa' : item.signatureMode,
                            'processDate': null,
                            'current': false,
                            'modes': ['visa'].concat(item.userSignatureModes)
                        };
                        return obj;
                    });
                    this.visaWorkflow = this.visaWorkflow.concat(workflows);
                    this.visaWorkflow.forEach((element: any, index: number) => {
                        this.getAvatarUser(index);
                    });
                }),
                catchError(err => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        }
    
        getVisaUserModels() {
            this.http.get('../rest/workflowTemplates').pipe(
                tap((data: any) => {
                    this.visaWorkflowModels = data.workflowTemplates;
                }),
                catchError(err => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        }