indexation.component.ts 17.5 KB
Newer Older
1
import { DatePipe } from '@angular/common';
2
import { HttpClient } from '@angular/common/http';
3
import { Component, ElementRef, OnInit, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
Alex ORLUC's avatar
Alex ORLUC committed
4
import { Router } from '@angular/router';
5
import { AlertController, LoadingController, MenuController, ModalController } from '@ionic/angular';
6
import { TranslateService } from '@ngx-translate/core';
7
8
import { of } from 'rxjs';
import { catchError, finalize, tap } from 'rxjs/operators';
9
import { VisaWorkflowComponent } from '../document/visa-workflow/visa-workflow.component';
10
import { AuthService } from '../service/auth.service';
11
import { NotificationService } from '../service/notification.service';
12
import { SignaturesContentService } from '../service/signatures.service';
13
import { SignaturePositionComponent } from './signature-position/signature-position.component';
14
import { ActionsService } from '../service/actions.service';
15
import { FunctionsService } from '../service/functions.service';
16
17
18
19

@Component({
    templateUrl: 'indexation.component.html',
    styleUrls: ['indexation.component.scss'],
20
    providers: [DatePipe]
21
22
23
})
export class IndexationComponent implements OnInit {

24
25
26
27
    @ViewChild('appVisaWorkflow', { static: false }) appVisaWorkflow: VisaWorkflowComponent;
    @ViewChild('rightContent', { static: true }) rightContent: TemplateRef<any>;
    @ViewChild('docToUpload') fileImport: ElementRef;

28
    loading: boolean = false;
29
    filesToUpload: any[] = [];
30
    errors: any[] = [];
31
    fromDocument: number = null;
32

33
    constructor(
34
        public http: HttpClient,
35
        private translate: TranslateService,
36
        public router: Router,
37
38
39
        private menu: MenuController,
        public signaturesService: SignaturesContentService,
        public viewContainerRef: ViewContainerRef,
40
        public notificationService: NotificationService,
41
        public authService: AuthService,
42
        public loadingController: LoadingController,
43
44
        public alertController: AlertController,
        public datePipe: DatePipe,
45
        public modalController: ModalController,
46
47
        public actionsService: ActionsService,
        private functionsService: FunctionsService
48
49
    ) { }

50
51
52
    ngOnInit(): void { }

    ionViewWillEnter() {
53
54
55
        this.menu.enable(true, 'left-menu');
        this.menu.enable(true, 'right-menu');

Alex ORLUC's avatar
Alex ORLUC committed
56
        this.filesToUpload = [];
57
        this.signaturesService.initTemplate(this.rightContent, this.viewContainerRef, 'rightContent');
58
59
60
61
62
63
64
65
66
67
68

        if (window.history.state.documentId !== undefined) {
            this.fromDocument = window.history.state.documentId;
            this.getDocumentData(this.fromDocument);
        }
    }

    getDocumentData(resId: number) {
        return new Promise((resolve) => {
            this.http.get(`../rest/documents/${resId}`).pipe(
                tap((data: any) => {
69
70
71
72
73
74
75
76
                    let ref = '';
                    let arrRef = data.document.reference.split('/');
                    arrRef = arrRef.slice(3, arrRef.length);

                    if (arrRef.length > 0) {
                        ref = arrRef.join('/');
                    }

77
78
                    this.filesToUpload.push({
                        title: data.document.title,
79
                        reference: ref,
80
81
                        mainDocument: true,
                        content: '',
82
83
                        linkId: data.document.linkId,
                        metadata: data.document.metadata,
84
85
86
87
                    });
                    this.getDocumentContent(resId);
                    this.appVisaWorkflow.loadWorkflow(data.document.workflow.map((item: any) => {
                        item.userSignatureModes.unshift('visa');
88
                        item.signatureMode = item.userId === null && item.signatureMode === 'stamp' ? 'sign' : item.signatureMode;
89
90
91
92
93
                        return {
                            ...item,
                            'processDate': null,
                            'current': false,
                            'role': item.mode === 'visa' ? 'visa' : item.signatureMode,
94
                            'modes': item.userId === null ? ['sign', 'visa'] : item.userSignatureModes
95
96
97
98
99
                        };
                    }));
                    for (let index = 0; index < data.document.attachments.length; index++) {
                        this.getAttachment(data.document.attachments[index].id);
                    }
100
101
102
103
104
105
106

                    const externalUsers: any[] = this.appVisaWorkflow.getCurrentWorkflow().filter((user: any) => user.userId === null);
                    if (externalUsers.length > 0) {
                        externalUsers.forEach(async (element: any) => {
                            const obj: any = await this.appVisaWorkflow.formatData(element);
                            element = obj;
                        });
107
                    }
108
109
110
111
112
113
114
115
116
117
118
119
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getDocumentContent(resId: number) {
        return new Promise((resolve) => {
120
            this.http.get(`../rest/documents/${resId}/content?type=original`).pipe(
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
                tap((data: any) => {
                    this.filesToUpload[0].content = data.encodedDocument;
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getAttachment(attachId: number) {
        return new Promise((resolve) => {
            this.http.get(`../rest/attachments/${attachId}`).pipe(
                tap((data: any) => {
                    this.filesToUpload.push({
                        title: data.attachment.title,
                        mainDocument: false,
                        content: data.attachment.encodedDocument
                    });
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
150
151
152
153
154
    }

    ionViewWillLeave() {
        this.signaturesService.detachTemplate('rightContent');
    }
155

156
    onSubmit() {
157
        if (this.isValid()) {
158
            this.promptSaveDoc();
159
160
161
        }
    }

162
163
    async promptSaveDoc() {
        const alert = await this.alertController.create({
164
165
            cssClass: 'alert-info-no-msg',
            header: this.translate.instant('lang.areYouSure'),
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
            inputs: [
                {
                    name: 'note',
                    id: 'note',
                    type: 'textarea',
                    placeholder: this.translate.instant('lang.addNote')
                },
            ],
            buttons: [
                {
                    text: this.translate.instant('lang.cancel'),
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => { }
                },
                {
                    text: this.translate.instant('lang.validate'),
                    handler: (data: any) => {
                        this.loadingController.create({
Alex ORLUC's avatar
Alex ORLUC committed
185
                            message: this.translate.instant('lang.processing'),
186
187
188
189
190
191
                            spinner: 'dots'
                        }).then(async (load: HTMLIonLoadingElement) => {
                            load.present();
                            const objTosend = this.formatData(data.note);
                            for (let index = 0; index < objTosend.length; index++) {
                                await this.saveDocument(objTosend[index], index);
192
193
194
                                if (objTosend[0].workflow[0].userId === this.authService.user.id) {
                                    this.actionsService.setEvent('refreshList');
                                }
195
196
197
                            }
                            load.dismiss();
                            if (this.errors.length === 0) {
Alex ORLUC's avatar
Alex ORLUC committed
198
                                this.notificationService.success('lang.documentsImported');
199
200
201
202
203
204
205
206
207
208
                                this.router.navigate(['/home']);
                            }
                        });
                    }
                }
            ]
        });
        await alert.present();
    }

209
210
211
212
    saveDocument(data: any, index: number) {
        return new Promise((resolve) => {
            this.http.post('../rest/documents', data).pipe(
                tap(() => {
213
                    this.errors = [];
214
215
216
217
218
219
220
221
222
223
224
                }),
                finalize(() => resolve(true)),
                catchError((err: any) => {
                    this.errors.push(data.title);
                    this.notificationService.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

225
    formatData(note: string) {
226
        const today: Date = new Date();
227
        let noteObj: any = null;
228
        let linkId: string = null;
229
230

        if (note !== '') {
231
232
233
234
            noteObj = {
                value: note,
                creator: `${this.authService.user.firstname} ${this.authService.user.lastname}`,
                creationDate: this.datePipe.transform(today, 'dd-MM-y')
235
236
            };
        }
237

238
239
240
241
        const formattedObj: any[] = [];
        const signedFiles = this.filesToUpload.filter((item: any) => item.mainDocument);
        const attachFiles = this.filesToUpload.filter((item: any) => !item.mainDocument);

242
243
244
245
        if (signedFiles.length > 1) {
            linkId = this.datePipe.transform(today, 'ddMMYhmmss') + '_' + Math.random().toString(36).substr(2, 9);
        }

246
        signedFiles.forEach((file: any) => {
247
248
249
250
251
252
            const metadata = {};
            if (this.fromDocument !== null) {
                file.metadata.forEach((element: any) => {
                    metadata[element.label] = element.value;
                });
            }
253
254
255
256
            let formattedReference = '';
            if (file.reference !== '') {
                formattedReference = this.datePipe.transform(today, 'y/MM/dd') + '/' + file.reference;
            }
257
258
            formattedObj.push({
                title: file.title,
259
                reference: formattedReference,
260
                encodedDocument: file.content,
261
                isZipped: false,
262
                linkId: this.fromDocument !== null ? file.linkId : linkId,
263
                sender: `${this.authService.user.firstname} ${this.authService.user.lastname}`,
264
                notes: noteObj,
265
266
267
268
269
                attachments: attachFiles.map((item: any) => ({
                    title: item.title,
                    encodedDocument: item.content
                })),
                workflow: this.appVisaWorkflow.getCurrentWorkflow().map((item: any, index: number) => ({
270
                    externalInformations: item.otp === undefined ? item.externalInformations : item.otp,
271
                    userId: item.userId,
272
                    mode: this.authService.getWorkflowMode(item.role),
273
                    signatureMode: this.authService.getSignatureMode(item.role),
274
                    signaturePositions: item.signaturePositions !== undefined ? this.formatPositions(item.signaturePositions.filter((pos: any) => pos.mainDocument === file.mainDocument && file.signPos !== undefined)).map((itemFile: any) => ({
275
276
277
278
279
                        page: itemFile.page,
                        positionX: itemFile.position.positionX,
                        positionY: itemFile.position.positionY,
                    })) : []
                })),
280
                metadata: metadata
281
282
283
284
285
286
            });
        });

        return formattedObj;
    }

287
288
289
290
291
    formatPositions(position: any) {
        delete position.mainDocument;
        return position;
    }

292
293
294
295
296
297
298
299
300
301
302
303
    dndUploadFile(event: any) {
        const fileInput = {
            target: {
                files: [
                    event[0]
                ]
            }
        };
        this.uploadTrigger(fileInput);
    }

    uploadTrigger(fileInput: any) {
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        this.loadingController.create({
            message: this.translate.instant('lang.loadingDocument'),
            spinner: 'dots'
        }).then(async (load: HTMLIonLoadingElement) => {
            load.present();
            if (fileInput.target.files && fileInput.target.files[0] && this.isExtensionAllowed(fileInput.target.files)) {
                for (let index = 0; index < fileInput.target.files.length; index++) {
                    const filename = fileInput.target.files[index].name;
                    const file = {
                        title: filename.substr(0, filename.lastIndexOf('.')),
                        reference: filename.substr(0, filename.lastIndexOf('.')).substr(0, 53),
                        mainDocument: true,
                        content: ''
                    };
                    const reader = new FileReader();
                    reader.readAsArrayBuffer(fileInput.target.files[index]);
                    reader.onload = (value: any) => {
                        file.mainDocument = this.filesToUpload.length === 0;
                        file.reference = this.filesToUpload.length === 0 ? file.reference : '';
                        file.content = this.getBase64Document(value.target.result);
                        this.filesToUpload.push(file);
                        if (this.filesToUpload.length === 1) {
                            setTimeout(() => {
                                this.menu.open('right-menu');
                            }, 500);
                        }
                    };
                }
                this.fileImport.nativeElement.value = '';
                load.dismiss();
            } else {
                this.loading = false;
                load.dismiss();
337
            }
338
        });
339
340
    }

341

342
343
344
    isExtensionAllowed(files: any[]) {
        for (let index = 0; index < files.length; index++) {
            if (files[index].name.toLowerCase().split('.').pop() !== 'pdf') {
Alex ORLUC's avatar
Alex ORLUC committed
345
                this.notificationService.error('lang.onlyPdfAuthorized');
346
347
348
349
350
351
                return false;
            }
        }
        return true;
    }

352
353
    getBase64Document(buffer: ArrayBuffer) {
        const TYPED_ARRAY = new Uint8Array(buffer);
354
        const STRING_CHAR = TYPED_ARRAY.reduce((data, byte) => data + String.fromCharCode(byte), '');
355
356
357
358
359
360
361
362

        return btoa(STRING_CHAR);
    }

    deleteFile(index: number) {
        this.filesToUpload.splice(index, 1);
    }

363
    async signPos(index: number) {
364
365
366
367
        const allUsers: any[] = this.appVisaWorkflow.getCurrentWorkflow();
        const usersWithNoteRole: any[] = this.appVisaWorkflow.getCurrentWorkflow().filter((user: any) => user.role === 'note');

        if ((allUsers.length === 1 && this.appVisaWorkflow.getCurrentWorkflow()[0].role === 'note') || (allUsers.length === usersWithNoteRole.length)) {
368
369
            this.notificationService.error('lang.cannotSetSignature');
        } else if (this.appVisaWorkflow.getCurrentWorkflow().length > 0) {
370
371
372
373
374
            this.appVisaWorkflow.getCurrentWorkflow().forEach((user: any, indexUser: number) => {
                if (user.signaturePositions === undefined) {
                    this.appVisaWorkflow.visaWorkflow[indexUser].signaturePositions = [];
                }
            });
375
376
377
378
            const modal = await this.modalController.create({
                component: SignaturePositionComponent,
                cssClass: 'custom-alert-fullscreen',
                componentProps: {
379
                    'workflow': this.appVisaWorkflow.getCurrentWorkflow(),
380
                    'resource': this.filesToUpload[index],
381
382
383
384
385
386
387
                    'pdfContent': 'data:application/pdf;base64,' + this.filesToUpload[index].content,
                }
            });
            await modal.present();
            const { data } = await modal.onWillDismiss();
            if (data !== undefined) {
                this.filesToUpload[index].signPos = data;
388
                this.appVisaWorkflow.setPositionsWorkfow(this.filesToUpload[index], data);
389
390
            }
        } else {
Alex ORLUC's avatar
Alex ORLUC committed
391
            this.notificationService.error('lang.mustSetWorkflowBeforeSignPositions');
392
393
394
        }
    }

395
    isValid() {
396
397
398
399
400
        if (this.filesToUpload.filter((item: any) => item.title === '').length > 0) {
            this.notificationService.error('lang.subjectMandatory');
            return false;
        } else if (this.filesToUpload.filter((item: any) => item.mainDocument).length === 0) {
            this.notificationService.error('lang.mainDocumentMandatory');
401
402
            return false;
        } else if (this.appVisaWorkflow.getCurrentWorkflow().length === 0) {
403
            this.notificationService.error('lang.workflowUserstMandatory');
404
405
            this.menu.open('right-menu');
            return false;
406
        } else if (this.appVisaWorkflow.getCurrentWorkflow().filter((user: any) => user.userId === null && user.noConnector !== undefined).length > 0) {
407
408
            this.notificationService.error('lang.noConnector');
            return false;
409
410
411
        } else if (this.hasEmptyOtpSignaturePosition()) {
            this.notificationService.error('lang.otpSignaturePositionMandatory');
            return false;
412
413
414
415
        } else {
            return true;
        }
    }
416
417
418
419
420
421
422
423
424
425
426


    hasEmptyOtpSignaturePosition() {
        const workflow = this.formatData(null)[0].workflow;

        const isSign = /_sign_/g;

        const hasEmptyPosition = workflow.filter((item: any) => item.signaturePositions.length === 0 && !this.functionsService.empty(item.externalInformations) && item.mode.match(isSign) !== null).length > 0;

        return hasEmptyPosition;
    }
427
}