sent-numeric-package-page.component.ts 22.2 KB
Newer Older
1
2
import { Component, OnInit, Inject, ElementRef, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
3
import { TranslateService } from '@ngx-translate/core';
4
import { NotificationService } from '@service/notification/notification.service';
5
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
6
7
import { switchMap, catchError, filter, exhaustMap, tap, debounceTime, distinctUntilChanged, finalize, map } from 'rxjs/operators';
import { FormControl } from '@angular/forms';
8
9
import { FunctionsService } from '@service/functions.service';
import { ContactService } from '@service/contact.service';
10
import { ConfirmComponent } from '../../../plugins/modal/confirm.component';
11
12
import { PrivilegeService } from '@service/privileges.service';
import { HeaderService } from '@service/header.service';
13
import { StripTagsPipe, ReversePipe } from 'ngx-pipes';
14
import { Observable, of } from 'rxjs';
15
import { environment } from '../../../environments/environment';
16
import { SplitLoginPwd } from '@plugins/splitLoginPwd.pipe';
17
18
19
20
21

@Component({
    selector: 'app-sent-numeric-package-page',
    templateUrl: './sent-numeric-package-page.component.html',
    styleUrls: ['./sent-numeric-package-page.component.scss'],
22
    providers: [ContactService, StripTagsPipe, ReversePipe, SplitLoginPwd],
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
})
export class SentNumericPackagePageComponent implements OnInit {

    loading: boolean = true;

    availableEmailModels: any[] = [];
    availableSignEmailModels: any[] = [];

    resourceData: any = null;
    availableSenders: any[] = [];
    currentSender: any = {};

    recipients: any[] = [];

    recipientsCtrl: FormControl = new FormControl();

    emailSignListForm = new FormControl();
    templateEmailListForm = new FormControl();

    filteredEmails: Observable<string[]>;

44
45
46
47
    numericPackageCreatorId: number = null;
    numericPackageStatus: string = 'WAITING';
    numericPackageCurrentAttachTool: string = '';
    numericPackageAttachTool: any = {
48
49
        document: {
            icon: 'fa fa-file',
50
            title: this.translate.instant('lang.attachMainDocument'),
51
52
53
54
            list: []
        },
        notes: {
            icon: 'fas fa-pen-square',
55
            title: this.translate.instant('lang.attachNote'),
56
57
58
59
            list: []
        },
        attachments: {
            icon: 'fa fa-paperclip',
60
            title: this.translate.instant('lang.attachAttachment'),
61
62
63
            list: []
        },
    };
64
    numericPackageAttach: any = [];
65
66
67

    numericPackage: any = {
        mainExchangeDoc: null,
68
69
70
71
72
73
74
75
        'object': '',
        'contacts': [],
        'joinFile': [],
        'joinAttachment': [],
        'notes': [],
        'content': '',
        'senderEmail': null
    };
76
77

    reference: string = null;
78
    messageReview: any[] = [];
79

80
    maarch2maarchUrl: string = `https://docs.maarch.org/gitbook/html/MaarchCourrier/${environment.VERSION.split('.')[0] + '.' + environment.VERSION.split('.')[1]}/guat/guat_exploitation/maarch2maarch.html`;
81
82
83
84

    @ViewChild('recipientsInput', { static: true }) recipientsInput: ElementRef<HTMLInputElement>;

    constructor(
85
        public translate: TranslateService,
86
87
88
89
90
91
92
93
94
95
        public http: HttpClient,
        private notify: NotificationService,
        @Inject(MAT_DIALOG_DATA) public data: any,
        public dialog: MatDialog,
        public dialogRef: MatDialogRef<SentNumericPackagePageComponent>,
        public functions: FunctionsService,
        private contactService: ContactService,
        public privilegeService: PrivilegeService,
        public headerService: HeaderService,
        private stringPipe: StripTagsPipe,
96
        private reversePipe: ReversePipe,
97
        private splitLoginPwd: SplitLoginPwd
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    ) { }

    async ngOnInit(): Promise<void> {

        await this.getAttachElements();

        if (this.data.emailId) {
            await this.getNumericPackageData(this.data.emailId);
        }

        if (this.canManageMail()) {
            this.initEmailModelsList();
            this.initM2MList();
            this.initSignEmailModelsList();

            await this.getResourceData();
            await this.getM2MSenders();

116
            this.setDefaultInfo();
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        }
        this.loading = false;
    }

    isBadEmailFormat(email: string) {
        const regex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/g;

        return email.trim().match(regex) === null;
    }

    closeModal(state: string = '') {
        this.dialogRef.close(state);
    }

    addRecipient(item: any) {
        this.recipients.push(item);
        this.recipientsInput.nativeElement.value = '';
        this.recipientsCtrl.setValue('');
    }

    mergeEmailTemplate(templateId: any) {

        this.templateEmailListForm.reset();

141
        this.http.post(`../rest/templates/${templateId}/mergeEmail`, { data: { resId: this.data.resId } }).pipe(
142
            tap((data: any) => {
143
                const textArea = document.createElement('textarea');
144
                textArea.innerHTML = data.mergedDocument;
145
                this.numericPackage.content += this.stringPipe.transform(textArea.value);
146
147
148
149
150
151
152
153
154
155
156
157
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    mergeSignEmailTemplate(templateId: any) {

        this.emailSignListForm.reset();

158
        this.http.get(`../rest/currentUser/emailSignatures/${templateId}`).pipe(
159
            tap((data: any) => {
160
                const textArea = document.createElement('textarea');
161
162
                textArea.innerHTML = data.emailSignature.content;
                this.numericPackage.content += this.stringPipe.transform(textArea.value);
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    remove(item: any, type: string): void {
        if (this.canManageMail()) {
            const index = this[type].indexOf(item);

            if (index >= 0) {
                this[type].splice(index, 1);
            }
        }
    }

    getNumericPackageData(emailId: number) {
        return new Promise((resolve) => {
183
            this.http.get(`../rest/messageExchanges/${emailId}`).pipe(
184
185
                map((data: any) => data.messageExchange),
                tap((data: any) => {
186
                    this.numericPackageCreatorId = data.userId;
187

188
                    data.recipient.communicationMeans = data.communicationType;
189
                    this.recipients = [data.recipient];
190
191
192

                    this.currentSender.label = data.sender;
                    this.numericPackage.object = data.object;
193
                    this.numericPackageStatus = data.status.toUpperCase();
194
195
                    this.numericPackage.content = data.body;
                    this.reference = data.reference;
196
197
                    this.messageReview = data.messageReview.map((item: any) => {
                        return {
198
199
                            date: this.functions.formatFrenchDateToObjectDate(item.substring(1, 19), '/'),
                            content: item.substring(21),
200
                        };
201
202
                    });
                    this.messageReview = this.reversePipe.transform(this.messageReview);
203

204
205
                    if (data.disposition.tablename === 'res_letterbox') {
                        this.numericPackage.mainExchangeDoc = {
206
                            ...this.numericPackageAttachTool['document'].list[0],
207
                            typeLabel: this.translate.instant('lang.mainDocument'),
208
                            type: 'document'
209
210
                        };

211
                        this.numericPackageAttach = this.numericPackageAttach.concat(this.numericPackageAttachTool['attachments'].list.filter((item: any) => data.attachments.indexOf(item.id.toString()) > -1));
212
213
                    } else {
                        this.numericPackage.mainExchangeDoc = {
214
                            ...this.numericPackageAttachTool['attachments'].list.filter((item: any) => item.id == data.disposition.res_id)[0],
215
                            type: 'attachments'
216
                        };
217
                        this.numericPackageAttach = this.numericPackageAttach.concat(this.numericPackageAttachTool['attachments'].list.filter((item: any) => data.attachments.indexOf(item.id.toString()) > -1 && item.id != data.disposition.res_id));
218
219
220
221

                    }

                    if (data.resMasterAttached && data.disposition.tablename !== 'res_letterbox') {
222
223
                        this.numericPackageAttach.push({
                            ...this.numericPackageAttachTool['document'].list[0],
224
                            typeLabel: this.translate.instant('lang.mainDocument'),
225
226
227
228
                            type: 'document'
                        });
                    }

229
                    this.numericPackageAttach = this.numericPackageAttach.concat(this.numericPackageAttachTool['notes'].list.filter((item: any) => data.notes.indexOf(item.id.toString()) > -1));
230

231
232
233
234
235
236
237
238
239
240
241
242
243
                    resolve(true);
                }),
                catchError((err) => {
                    this.notify.handleSoftErrors(err);
                    resolve(false);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getResourceData() {
        return new Promise((resolve) => {
244
            this.http.get(`../rest/resources/${this.data.resId}?light=true`).pipe(
245
246
247
248
249
250
251
252
253
254
255
256
257
258
                tap((data: any) => {
                    this.resourceData = data;
                    this.numericPackage.object = this.resourceData.subject;
                    resolve(true);
                }),
                catchError((err) => {
                    this.notify.handleSoftErrors(err);
                    resolve(false);
                    return of(false);
                })
            ).subscribe();
        });
    }

259
260
261
    setDefaultInfo() {
        if (!this.functions.empty(this.resourceData.senders)) {
            this.resourceData.senders.forEach((sender: any) => {
262
263
264
                if (sender.type === 'contact') {
                    this.setSender(sender.id);
                }
265
266
267
268
            });
        }
    }

269
    setSender(id: number) {
270
        this.http.get(`../rest/contacts/${id}`).pipe(
271
            tap((data: any) => {
272
                if (!this.functions.empty(data.communicationMeans) && !this.functions.empty(data.externalId['m2m'])) {
273
274
                    this.recipients.push(
                        {
275
                            id: id,
276
                            label: this.contactService.formatContact(data),
277
                            email: data.email,
278
279
                            m2m: data.externalId['m2m'],
                            communicationMeans: data.communicationMeans
280
                        }
281
                    );
282
283
284
285
286
287
288
289
290
291
292
                }
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    getM2MSenders() {
        return new Promise((resolve) => {
293
            this.http.get('../rest/messageExchangesInitialization').pipe(
294
295
                tap((data: any) => {
                    this.availableSenders = data.entities;
296
                    this.currentSender = this.availableSenders[0];
297
298
299
300
301
302
303
304
305
306
307
308
309
                    resolve(true);
                }),
                catchError((err) => {
                    this.notify.handleSoftErrors(err);
                    resolve(false);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getAttachElements() {
        return new Promise((resolve) => {
310
            this.http.get(`../rest/resources/${this.data.resId}/emailsInitialization`).pipe(
311
312
313
                tap((data: any) => {
                    Object.keys(data).forEach(element => {
                        if (element === 'resource') {
314
                            this.numericPackageAttachTool.document.list = [];
315
                            if (!this.functions.empty(data[element])) {
316
                                this.numericPackageAttachTool.document.list = [data[element]];
317
318
                            }
                        } else {
319
                            this.numericPackageAttachTool[element].list = data[element].map((item: any) => {
320
321
322
323
                                return {
                                    ...item,
                                    original: item.original !== undefined ? item.original : true,
                                    title: item.chrono !== undefined ? `${item.chrono} - ${item.label} (${item.typeLabel})` : `${item.label} (${item.typeLabel})`
324
                                };
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
                            });
                        }
                    });
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    resolve(false);
                    return of(false);
                })
            ).subscribe();
        });
    }

    initM2MList() {
        this.recipientsCtrl.valueChanges.pipe(
            filter(value => value !== null),
            debounceTime(300),
            tap((value) => {
                if (value.length === 0) {
                    this.filteredEmails = of([]);
                }
            }),
            filter(value => value.length > 2),
            distinctUntilChanged(),
350
            switchMap(data => this.http.get('../rest/autocomplete/contacts/m2m', { params: { 'search': data } })),
351
352
353
354
355
356
            tap((data: any) => {
                data = data.map((contact: any) => {
                    return {
                        ...contact,
                        address: this.contactService.formatContact(contact),
                        label: this.contactService.formatContact(contact)
357
                    };
358
359
360
361
362
363
364
365
366
367
368
                });
                this.filteredEmails = of(data);
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    initEmailModelsList() {
369
        this.http.get(`../rest/resources/${this.data.resId}/emailTemplates`).pipe(
370
371
372
373
374
375
376
377
378
379
380
            tap((data: any) => {
                this.availableEmailModels = data.templates;
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    initSignEmailModelsList() {
381
        this.http.get(`../rest/currentUser/emailSignatures`).pipe(
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
            tap((data: any) => {
                this.availableSignEmailModels = data.emailSignatures;
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    resetAutocomplete() {
        this.filteredEmails = of([]);
    }

    onSubmit() {
        this.loading = true;
398
        this.numericPackageStatus = 'WAITING';
399
400
        if (this.data.emailId === null) {
            if (this.numericPackage.object === '') {
401
                const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: this.translate.instant('lang.confirm'), msg: this.translate.instant('lang.warnEmptySubject') } });
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418

                dialogRef.afterClosed().pipe(
                    filter((data: string) => data === 'ok'),
                    tap(() => {
                        this.createEmail(true);
                    })
                ).subscribe();
            } else {
                this.createEmail(true);
            }

        } else {
            this.updateEmail(true);
        }
    }

    createEmail(closeModal: boolean = true) {
419
        this.http.post(`../rest/resources/${this.data.resId}/messageExchange`, this.formatNumericPackage()).pipe(
420
            tap(() => {
421
                this.notify.success(this.translate.instant('lang.numericPackageSent'));
422
423
424
425
426
427
428
429
430
431
432
433

                this.closeModal('success');
            }),
            finalize(() => this.loading = false),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    deleteEmail() {
434
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: this.translate.instant('lang.delete'), msg: this.translate.instant('lang.confirmAction') } });
435
436

        dialogRef.afterClosed().pipe(
437
            filter((data: string) => data === 'ok'),
438
            exhaustMap(() => this.http.delete(`../rest/messageExchanges/${this.data.emailId}`)),
439
            tap(() => {
440
                this.notify.success(this.translate.instant('lang.numericPackageDeleted'));
441
442
443
444
445
446
447
                this.closeModal('success');
            }),
            finalize(() => this.loading = false),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
448
449
450
451
        ).subscribe();
    }

    updateEmail(closeModal: boolean = true) {
452
        this.http.put(`../rest/emails/${this.data.emailId}`, this.formatNumericPackage()).pipe(
453
            tap(() => {
454

455
                this.notify.success(this.translate.instant('lang.numericPackageSent'));
456
457
458
459
460
461
462
463
464
465
466
467
468
469

                if (closeModal) {
                    this.closeModal('success');
                }
            }),
            finalize(() => this.loading = false),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    toggleAttach(item: any, type: string, mode: string) {
470
        if (this.numericPackage.mainExchangeDoc === null && type !== 'notes') {
471
472
            this.numericPackage.mainExchangeDoc = {
                ...item,
473
                typeLabel: item.typeLabel !== undefined ? item.typeLabel : this.translate.instant('lang.mainDocument'),
474
                type: type
475
            };
476
        } else {
477
            this.numericPackageAttach.push({
478
                ...item,
479
                typeLabel: item.typeLabel !== undefined ? item.typeLabel : this.translate.instant('lang.mainDocument'),
480
481
482
483
484
485
                type: type
            });
        }
    }

    removeAttach(index: number) {
486
        this.numericPackageAttach.splice(index, 1);
487
488
489
490
491
492
493
494
495
496
497
498
    }

    formatNumericPackage() {
        const numericPackage: any = {};
        if (this.numericPackage.mainExchangeDoc !== null) {
            let typeDoc = 'res_letterbox';
            if (this.numericPackage.mainExchangeDoc.type === 'attachments') {
                typeDoc = 'res_attachments';
            } else if (this.numericPackage.mainExchangeDoc.type === 'notes') {
                typeDoc = 'notes';
            }
            numericPackage.joinFile = [parseInt(this.numericPackage.mainExchangeDoc.id)];
499
            numericPackage.mainExchangeDoc = `${typeDoc}__${this.numericPackage.mainExchangeDoc.id}`;
500
501
502
503
        }
        numericPackage.object = this.numericPackage.object;
        numericPackage.content = this.numericPackage.content;
        numericPackage.contacts = this.recipients.map(recipient => recipient.id);
504
505
        numericPackage.joinAttachment = this.numericPackageAttach.filter((attach: any) => attach.type === 'attachments').map((attach: any) => attach.id);
        numericPackage.notes = this.numericPackageAttach.filter((attach: any) => attach.type === 'notes').map((attach: any) => attach.id);
506
507
508
509
510
511
        numericPackage.senderEmail = this.currentSender.id;

        return numericPackage;
    }

    isSelectedAttach(item: any, type: string) {
512
        return this.numericPackageAttach.filter((attach: any) => attach.id === item.id && attach.type === type).length > 0 || (this.numericPackage.mainExchangeDoc !== null && this.numericPackage.mainExchangeDoc.id === item.id && type === this.numericPackage.mainExchangeDoc.type);
513
514
515
    }

    isSelectedAttachType(type: string) {
516
        return this.numericPackageAttach.filter((attach: any) => attach.type === type).length > 0 || (this.numericPackage.mainExchangeDoc !== null && type === this.numericPackage.mainExchangeDoc.type);
517
518
519
    }

    canManageMail() {
520
        if ((this.data.emailId === null) || (this.numericPackageStatus !== 'SENT' && this.headerService.user.id === this.numericPackageCreatorId)) {
521
522
523
524
525
526
527
528
529
530
531
            this.recipientsCtrl.enable();
            return true;
        } else {
            this.recipientsCtrl.disable();
            return false;
        }
    }

    compareSenders(sender1: any, sender2: any) {
        return (sender1.label === sender2.label || ((sender1.label === null || sender2.label === null) && (sender1.entityId === null || sender2.entityId === null))) && sender1.entityId === sender2.entityId && sender1.email === sender2.email;
    }
532
533

    saveNumericPackageFile() {
534
        this.http.get(`../rest/messageExchanges/${this.data.emailId}/archiveContent`, { responseType: 'blob' }).pipe(
535
            tap((data: any) => {
536
                const downloadLink = document.createElement('a');
537
                downloadLink.href = window.URL.createObjectURL(data);
538

539
540
541
542
                let today: any;
                let dd: any;
                let mm: any;
                let yyyy: any;
543

544
545
546
547
                today = new Date();
                dd = today.getDate();
                mm = today.getMonth() + 1;
                yyyy = today.getFullYear();
548

549
550
551
552
553
554
555
                if (dd < 10) {
                    dd = '0' + dd;
                }
                if (mm < 10) {
                    mm = '0' + mm;
                }
                today = dd + '-' + mm + '-' + yyyy;
556
                downloadLink.setAttribute('download', 'NumericPackage_' + today + '.zip');
557
558
                document.body.appendChild(downloadLink);
                downloadLink.click();
559
560
561
562
563
564
565
566
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

567
568
569
    canSendNumericPackage() {
        return this.privilegeService.getCurrentUserMenus().filter((item: any) => item.id === 'manage_numeric_package').length > 0;
    }
570
571
572

    getCommunicationMean(value: any) {
        if (!this.functions.empty(value.url)) {
573
            return this.splitLoginPwd.transform(value.url);
574
575
576
577
        } else if (!this.functions.empty(value.email)) {
            return value.email;
        }
    }
578
}