Skip to content
Snippets Groups Projects
signatures.component.ts 13.9 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Component, Input, OnInit, Renderer2, ViewChild } from '@angular/core';
    
    import { MatBottomSheet } from '@angular/material/bottom-sheet';
    
    Alex ORLUC's avatar
    Alex ORLUC committed
    import { SignaturesContentService } from '../service/signatures.service';
    import { DomSanitizer } from '@angular/platform-browser';
    import * as $ from 'jquery';
    
    import { HttpClient } from '@angular/common/http';
    
    import { NotificationService } from '../service/notification.service';
    
    import { TranslateService } from '@ngx-translate/core';
    
    import { AuthService } from '../service/auth.service';
    
    import { LocalStorageService } from '../service/local-storage.service';
    
    import { IonSlides, ModalController } from '@ionic/angular';
    import { SignaturePadPageComponent } from '../pad/pad.component';
    
    Alex ORLUC's avatar
    Alex ORLUC committed
    
    @Component({
    
        selector: 'app-signatures',
        templateUrl: 'signatures.component.html',
        styleUrls: ['signatures.component.scss'],
    
    Alex ORLUC's avatar
    Alex ORLUC committed
    })
    
    export class SignaturesComponent implements OnInit {
    
    
        @Input() currentWorflow: any;
    
        @Input() content: any;
    
        @ViewChild('slides', { static: false }) slides: IonSlides;
    
    
        loading: boolean = true;
        scrolling: boolean = false;
    
        signPosMode: boolean = false;
    
        datePosMode: boolean = false;
    
        title: string = 'lang.signatures';
    
        slideOpts = {
            initialSlide: 0,
            speed: 400,
            direction: 'vertical'
        };
        signaturesList: any[] = [];
    
    
        inAllPage = false;
        count = 0;
    
        documentWidth: number;
    
        signatureWidth: number;
    
        constructor(private translate: TranslateService,
            public http: HttpClient,
            public signaturesService: SignaturesContentService,
            private bottomSheetRef: MatBottomSheet,
            private sanitization: DomSanitizer,
            public notificationService: NotificationService,
            public authService: AuthService,
    
            private localStorage: LocalStorageService,
    
            private renderer: Renderer2,
            public modalController: ModalController
        ) {
        }
    
        dismissModal() {
            this.modalController.dismiss('cancel');
        }
    
        scroll(ev: any) {
            if (!this.scrolling) {
                this.scrolling = true;
                if (ev.deltaY < 0) {
                    this.slides.slidePrev();
                } else {
                    this.slides.slideNext();
                }
                setTimeout(() => {
                    this.scrolling = false;
                }, 500);
            }
    
        ngOnInit() {
    
            this.initSignatures();
    
            this.signPosMode = this.currentWorflow.signaturePositions.length > 0 && this.emptySigns();
    
            this.getImgDimensions(this.content);
    
        }
    
        initSignatures() {
            this.signaturesList = [];
            let obj: any[] = [];
            let index = 0;
            const mergedSign = this.signaturesService.signaturesListSubstituted.concat(this.signaturesService.signaturesList);
            mergedSign.forEach((element: any) => {
                if (index === 6) {
                    this.signaturesList.push(obj);
                    obj = [element];
                    index = 0;
                } else {
                    obj.push(element);
                    index++;
                }
            });
            if (obj.length > 0) {
                this.signaturesList.push(obj);
            }
        }
    
        ionViewDidEnter() {
            this.loading = false;
    
        async openSignatures() {
            const modal = await this.modalController.create({
                component: SignaturePadPageComponent,
                cssClass: 'my-custom-class'
            });
            await modal.present();
            const { data } = await modal.onWillDismiss();
            if (data === 'reload') {
                this.initSignatures();
            }
    
        mustPrePosSignature(signPosCurrentPage: any, signPosOtherPage: any) {
            return !(!this.signPosMode || (signPosCurrentPage.length === 0 && signPosOtherPage.length === 0));
        }
    
    
            let percentWidth: any;
            const signatureScaling: any = this.authService.user.preferences.signatureScaling;
    
            const signatureWidth: number = this.signatureWidth >= this.documentWidth ? 100 : (this.signatureWidth * 100) / this.documentWidth;
    
            if (signatureScaling === false) {
    
                percentWidth = signatureScaling === false ? signatureWidth : signatureScaling;
    
            const signPosCurrentPage = this.currentWorflow.signaturePositions.filter((item: any) => item.page === this.signaturesService.currentPage);
            const signPosOtherPage = this.currentWorflow.signaturePositions.filter((item: any) => item.page !== this.signaturesService.currentPage);
    
    
            if (!this.mustPrePosSignature(signPosCurrentPage, signPosOtherPage)) {
    
                signature.positionX = 60;
                signature.positionY = 80;
                this.storeSignature(signature, this.signaturesService.currentPage);
                this.notificationService.success('lang.signatureInDocAdded');
                this.modalController.dismiss('success');
            } else {
    
                // set sign block in current page
                if (signPosCurrentPage.length > 0) {
    
                    signature.positionX = signPosCurrentPage[0].positionX;
                    signature.positionY = signPosCurrentPage[0].positionY;
                    this.storeSignature(signature, this.signaturesService.currentPage);
    
                }
    
                // set sign block in other page
                if (signPosOtherPage.length > 0) {
    
                    signPosOtherPage.forEach((element: { positionX: any; positionY: any; page: number }) => {
    
                        signature.positionX = element.positionX;
                        signature.positionY = element.positionY;
                        this.storeSignature(signature, element.page);
                    });
    
                }
                if (this.currentWorflow.signaturePositions.length === 1) {
                    this.notificationService.success('lang.signatureInDocAddedAlt');
                } else {
    
                    this.translate.get('lang.signaturesInDocAdded', { 0: this.currentWorflow.signaturePositions.map((item: any) => item.page) }).subscribe((res: string) => {
                        this.notificationService.success(res);
                    });
    
                // if no sign in current page but have sign in other page
                if (signPosCurrentPage.length === 0 && signPosOtherPage.length > 0) {
                    // go to first page with signature block
                    this.modalController.dismiss({ redirectPage: signPosOtherPage[0].page });
                } else {
    
                    this.modalController.dismiss('success');
                }
    
        addNewDate() {
            const datePosCurrentPage = this.currentWorflow.datePositions.filter((item: any) => item.page === this.signaturesService.currentPage);
            const datePosOtherPage = this.currentWorflow.datePositions.filter((item: any) => item.page !== this.signaturesService.currentPage);
    
    
            if (datePosCurrentPage.length === 0 && datePosOtherPage.length === 0) {
    
                const dateBlock: any = {
    
                    width: (130 * 100) / this.signaturesService.workingAreaWidth,
                    height: (30 * 100) / this.signaturesService.workingAreaHeight,
                    positionX: 0,
    
                    positionY: 0,
                    font: 'Arial',
    
                    color: '#666',
    
                dateBlock.positionX = 60;
                dateBlock.positionY = 80;
    
                this.storeDate(dateBlock, this.signaturesService.currentPage);
                this.notificationService.success('lang.dateInDocAdded');
                this.modalController.dismiss('success');
            } else {
                if (datePosCurrentPage.length > 0) {
    
                    const dateBlock: any = {
    
                        width: datePosCurrentPage[0].width,
                        height: datePosCurrentPage[0].height,
                        positionX: datePosCurrentPage[0].positionX,
    
                        positionY: datePosCurrentPage[0].positionY,
                        font: 'Arial',
    
                        color: '#666',
    
                    this.storeDate(dateBlock, this.signaturesService.currentPage);
                }
    
                datePosOtherPage.forEach((position: any) => {
    
                    const dateBlock: any = {
    
                        width: position.width,
                        height: position.height,
                        positionX: position.positionX,
    
                        positionY: position.positionY,
                        font: 'Arial',
    
                        color: '#666',
    
                    };
                    this.storeDate(dateBlock, position.page);
    
                });
    
                if (this.currentWorflow.signaturePositions.length === 1) {
                    this.notificationService.success('lang.dateInDocAddedAlt');
                } else {
                    this.translate.get('lang.dateInDocAdded', { 0: this.currentWorflow.signaturePositions.map((item: any) => item.page) }).subscribe((res: string) => {
                        this.notificationService.success(res);
                    });
                }
    
                if (datePosCurrentPage.length === 0 && datePosOtherPage.length > 0) {
                    this.modalController.dismiss({ redirectPage: datePosOtherPage[0].page });
                } else {
                    this.modalController.dismiss('success');
                }
            }
        }
    
    
        storeSignature(signature: any, page: number) {
            if (!this.signaturesService.signaturesContent[page]) {
                this.signaturesService.signaturesContent[page] = [];
            }
            this.signaturesService.signaturesContent[page].push(JSON.parse(JSON.stringify(signature)));
    
            this.localStorage.save(this.signaturesService.mainDocumentId.toString(), JSON.stringify({ 'date': this.signaturesService.datesContent, 'sign': this.signaturesService.signaturesContent, 'note': this.signaturesService.notesContent }));
        }
    
        storeDate(date: any, page: number) {
            if (!this.signaturesService.datesContent[page]) {
                this.signaturesService.datesContent[page] = [];
            }
            this.signaturesService.datesContent[page].push(JSON.parse(JSON.stringify(date)));
    
            this.localStorage.save(this.signaturesService.mainDocumentId.toString(), JSON.stringify({ 'date': this.signaturesService.datesContent, 'sign': this.signaturesService.signaturesContent, 'note': this.signaturesService.notesContent }));
    
    Vinciane's avatar
    Vinciane committed
            const r = confirm(this.translate.instant('lang.wantDeleteSignature'));
    
            if (r) {
    
                this.http.delete('../rest/users/' + this.authService.user.id + '/signatures/' + signature.id)
    
                    .subscribe(() => {
    
                        this.signaturesService.signaturesList = this.signaturesService.signaturesList.filter((element) => element.id !== signature.id);
    
                        this.notificationService.success('lang.signatureDeleted');
    
                        this.initSignatures();
    
                    }, (err: any) => {
                        this.notificationService.error(err.error.errors);
                    });
            }
        }
    
        toggleAllPage() {
            this.inAllPage = !this.inAllPage;
        }
    
        tapEvent(signature: any, i: any, mode: string) {
    
            this.count++;
    
            setTimeout(() => {
                if (this.count === 1) {
                    this.count = 0;
                } else if (this.count > 1) {
                    this.count = 0;
    
                    const id = mode === 'substitute' ? ('imgSignSub_' + i) : ('imgSign_' + i);
    
    
        handleFileInput(files: FileList) {
            const fileToUpload = files.item(0);
    
    
            if (fileToUpload.size <= 1000000) {
    
                if (['image/png', 'image/jpg', 'image/jpeg', 'image/gif'].indexOf(fileToUpload.type) !== -1) {
                    const myReader: FileReader = new FileReader();
                    myReader.onloadend = (e) => {
    
                        const newEncodedSign = myReader.result.toString().replace('data:' + fileToUpload.type + ';base64,', '');
    
                        this.localStorage.save('signature', JSON.stringify(newEncodedSign));
    
    
                        // Save signature in BDD
                        const newSign = {
                            'id': 0,
                            'encodedSignature': newEncodedSign,
                            'format': 'png'
                        };
    
                        this.http.post('../rest/users/' + this.authService.user.id + '/signatures', newSign)
    
                            .subscribe((data: any) => {
                                newSign.id = data.signatureId;
                                this.signaturesService.signaturesList.unshift(
                                    {
                                        id: newSign.id,
                                        encodedSignature: newSign.encodedSignature
                                    }
                                );
                                this.initSignatures();
                                this.notificationService.success('lang.signatureRegistered');
                            });
    
                    };
                    myReader.readAsDataURL(fileToUpload);
                } else {
                    this.notificationService.error('lang.notAnImage');
                }
            } else {
    
                this.notificationService.error('lang.maxFileSizeReached');
    
    
        emptySigns() {
            let state = true;
            for (let pageNum = 1; pageNum <= this.signaturesService.totalPage; pageNum++) {
                if (this.signaturesService.signaturesContent[pageNum]) {
                    if (this.signaturesService.signaturesContent[pageNum].length > 0) {
                        state = false;
                        break;
                    }
                }
            }
            return state;
        }
    
        getImgDimensions(signList: any) {
    
            const decodeBase64 = atob(signList.slice(0, 50)).slice(16, 24);
            const uint8 = Uint8Array.from(decodeBase64, c => c.charCodeAt(0));
            const dataView = new DataView(uint8.buffer);
            this.documentWidth = dataView.getInt32(0);
        }
    
    
        setSignatureWidth(event: any) {
            this.signatureWidth = event.path[0].naturalWidth;
    
    Alex ORLUC's avatar
    Alex ORLUC committed
    }