template-administration.component.ts 30.4 KB
Newer Older
1
import { Component, OnInit, ViewChild, Inject, TemplateRef, ViewContainerRef, OnDestroy } from '@angular/core';
2
3
import { HttpClient } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
4
import { TranslateService } from '@ngx-translate/core';
5
import { NotificationService } from '@service/notification/notification.service';
6
7
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSidenav } from '@angular/material/sidenav';
8
9
import { HeaderService } from '@service/header.service';
import { AppService } from '@service/app.service';
10
import { filter, tap, catchError, exhaustMap } from 'rxjs/operators';
11
12
import { FunctionsService } from '@service/functions.service';
import { of } from 'rxjs';
13
14
15
import { TemplateFileEditorModalComponent } from './templateFileEditorModal/template-file-editor-modal.component';
import { DomSanitizer } from '@angular/platform-browser';
import { AlertComponent } from '../../../plugins/modal/alert.component';
16
import { MaarchFlatTreeComponent } from '../../../plugins/tree/maarch-flat-tree.component';
17
import { AuthService } from '@service/auth.service';
18
import { ConfirmComponent } from '@plugins/modal/confirm.component';
19

20
declare let tinymce: any;
Damien's avatar
Damien committed
21

22
@Component({
23
    templateUrl: 'template-administration.component.html',
24
    styleUrls: ['template-administration.component.scss']
25
})
26
export class TemplateAdministrationComponent implements OnInit, OnDestroy {
27

28
    @ViewChild('snav2', { static: true }) public sidenavRight: MatSidenav;
29
    @ViewChild('adminMenuTemplate', { static: true }) adminMenuTemplate: TemplateRef<any>;
30
    @ViewChild('maarchTree', { static: true }) maarchTree: MaarchFlatTreeComponent;
31

32
33
34
    loading: boolean = false;

    creationMode: boolean;
35
36

    template: any = {
37
        id: 0,
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
        label: '',
        description: '',
        datasource: 'letterbox_attachment',
        target: '',
        type: '',
        file: null
    };

    targetTypes: string[] = [
        'acknowledgementReceipt',
        'notes',
        'sendmail',
        'indexingFile',
        'notifications',
        'attachments'
    ];

    allowedExtensions: string[] = [
        'doc',
        'docx',
        'dotx',
        'odt',
        'ott',
        'html',
        'xlsl',
        'xlsx',
        'xltx',
        'ods',
        'ots',
        'csv',
    ];

    selectedModelFile: any = null;
    availableTypes: string[] = [];

73
74
75
76
77
78
79
80
    statuses: any[] = [];
    categoriesList: any[] = [];
    keywordsList: any[] = [];
    defaultTemplatesList: any;
    attachmentTypesList: any;
    datasourcesList: any;
    jnlpValue: any = {};
    extensionModels: any[] = [];
81
    buttonFileName: any = this.translate.instant('lang.importFile');
82
83
84
    lockFound: boolean = false;
    intervalLockFile: any;

85
86
    templateDocView: any = null;

87
88
89
    dialogRef: MatDialogRef<any>;
    data: any[] = [];
    config: any = {};
90

91
    documentImported: boolean = false;
92

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    acknowledgementReceiptFrom = [
        {
            id: 'manual',
            label : this.translate.instant('lang.manual')
        },
        {
            id: 'destination',
            label : this.translate.instant('lang.destination')
        },
        {
            id: 'mailServer',
            label : this.translate.instant('lang.mailServer')
        },
        {
            id: 'user',
            label : this.translate.instant('lang.user')
        }
    ];

    options: any = {};

114
    constructor(
115
        public http: HttpClient,
116
        private sanitizer: DomSanitizer,
117
118
119
        private route: ActivatedRoute,
        private router: Router,
        private notify: NotificationService,
120
        public headerService: HeaderService,
121
        public dialog: MatDialog,
122
        public appService: AppService,
123
        private viewContainerRef: ViewContainerRef,
124
        public functionsService: FunctionsService,
125
126
        public translate: TranslateService,
        private authService: AuthService
127
    ) { }
128
129
130

    ngOnInit(): void {
        this.loading = true;
131
        this.headerService.injectInSideBarLeft(this.adminMenuTemplate, this.viewContainerRef, 'adminMenu');
132
133

        this.route.params.subscribe(params => {
134
            if (typeof params['id'] === 'undefined') {
135
                this.headerService.setHeader(this.translate.instant('lang.templateCreation'));
136

137
138
                this.creationMode = true;

139
                this.http.get('../rest/administration/templates/new')
140
141
                    .subscribe((data: any) => {
                        this.setInitialValue(data);
Vinciane's avatar
Vinciane committed
142
                        this.loading = false;
143

144
145
                    });
            } else {
146

147
                this.creationMode = false;
148
                this.http.get('../rest/templates/' + params['id'] + '/details')
149
                    .subscribe((data: any) => {
150
                        this.setInitialValue(data);
151
                        this.template = {
152
                            id: data.template.template_id,
153
154
155
156
157
                            label: data.template.template_label,
                            description: data.template.template_comment,
                            datasource: data.template.template_datasource,
                            target: data.template.template_target,
                            type: data.template.template_type,
158
                            subject: data.template.subject,
159
160
161
162
163
                            file: {}
                        };
                        this.updateTemplateType();

                        this.selectedModelFile = data.template.template_file_name;
164
                        this.template.template_attachment_type = data.template.template_attachment_type;
165
166
167
168
169
                        if (this.template.type === 'HTML' || this.template.type === 'TXT') {
                            this.template.file.content = data.template.template_content;
                        } else if (this.template.type === 'OFFICE') {
                            this.template.file.format = data.template.template_file_name.split('.').pop();
                            this.template.file.name = data.template.template_file_name;
170
                            this.getViewTemplateContent();
171
                        } else if (this.template.target === 'acknowledgementReceipt') {
172
173
                            this.template.file.electronic.content = data.template.template_content;

174
                            if (!this.functionsService.empty(data.template.template_file_name)) {
175
                                this.template.file.paper.format = data.template.template_file_name.split('.').pop();
176
177
                                this.template.file.paper.name = data.template.template_file_name;
                                this.getViewTemplateContent();
178
                            }
179
                        }
180
                        this.options = data.template.options;
181

182
                        this.headerService.setHeader(this.translate.instant('lang.templateModification'), this.template.template_label);
Vinciane's avatar
Vinciane committed
183
                        this.loading = false;
184
185
                    });
            }
Vinciane's avatar
Vinciane committed
186
            if (!this.template.template_attachment_type) {
187
188
                this.template.template_attachment_type = 'all';
            }
189
190
191
        });
    }

192
193
194
195
196
197
198
199
200
201
202
203
    getViewTemplateContent() {
        this.http.get(`../rest/templates/${this.template.id}/content`).pipe(
            tap((data: any) => {
                this.templateDocView = this.sanitizer.bypassSecurityTrustResourceUrl('data:application/pdf;base64,' + data.encodedDocument);
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

Vinciane's avatar
Vinciane committed
204
    initMce(selectorId: string) {
Damien's avatar
Damien committed
205
206
        setTimeout(() => {
            tinymce.remove('textarea');
207
            // LOAD EDITOR TINYMCE for MAIL SIGN
208
            tinymce.baseURL = '../node_modules/tinymce';
Damien's avatar
Damien committed
209
210
            tinymce.suffix = '.min';
            tinymce.init({
211
                selector: selectorId,
212
                convert_urls: false,
Vinciane's avatar
Vinciane committed
213
                statusbar: false,
214
215
                language: this.translate.instant('lang.langISO').replace('-', '_'),
                language_url: `../node_modules/tinymce-i18n/langs/${this.translate.instant('lang.langISO').replace('-', '_')}.js`,
216
                height: '200',
Vinciane's avatar
Vinciane committed
217
                plugins: [
218
219
                    'autoresize',
                    'code'
Vinciane's avatar
Vinciane committed
220
221
                ],
                external_plugins: {
222
                    'maarch_b64image': '../../src/frontend/plugins/tinymce/maarch_b64image/plugin.min.js'
Vinciane's avatar
Vinciane committed
223
224
                },
                menubar: false,
225
226
227
228
229
230
231
232
233
234
                toolbar: 'undo | bold italic underline | alignleft aligncenter alignright | maarch_b64image | forecolor | code',
                theme_buttons1_add: 'fontselect,fontsizeselect',
                theme_buttons2_add_before: 'cut,copy,paste,pastetext,pasteword,separator,search,replace,separator',
                theme_buttons2_add: 'separator,insertdate,inserttime,preview,separator,forecolor,backcolor',
                theme_buttons3_add_before: 'tablecontrols,separator',
                theme_buttons3_add: 'separator,print,separator,ltr,rtl,separator,fullscreen,separator,insertlayer,moveforward,movebackward,absolut',
                theme_toolbar_align: 'left',
                theme_advanced_toolbar_location: 'top',
                theme_styles: 'Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1',
                setup: (ed: any) => {
Alex ORLUC's avatar
Alex ORLUC committed
235
                    ed.on('keyup', (e: any) => {
236
237
                        if (this.template.type === 'HTML' && tinymce.get('templateHtml') != null) {
                            this.template.file.content = tinymce.get('templateHtml').getContent();
Alex ORLUC's avatar
Alex ORLUC committed
238
                        }
239
240
                        if (this.template.type === 'OFFICE_HTML' && tinymce.get('templateOfficeHtml') != null) {
                            this.template.file.electronic.content = tinymce.get('templateOfficeHtml').getContent();
Alex ORLUC's avatar
Alex ORLUC committed
241
242
                        }
                    });
243
244
245
246
247
248
249
250
                    ed.on('change', (e: any) => {
                        if (this.template.type === 'HTML' && tinymce.get('templateHtml') != null) {
                            this.template.file.content = tinymce.get('templateHtml').getContent();
                        }
                        if (this.template.type === 'OFFICE_HTML' && tinymce.get('templateOfficeHtml') != null) {
                            this.template.file.electronic.content = tinymce.get('templateOfficeHtml').getContent();
                        }
                    });
Alex ORLUC's avatar
Alex ORLUC committed
251
                }
252

Vinciane's avatar
Vinciane committed
253
254
255
256
            });
        }, 20);
    }

Vinciane's avatar
Vinciane committed
257
    setInitialValue(data: any) {
Alex ORLUC's avatar
Alex ORLUC committed
258
259
        this.extensionModels = [];
        data.templatesModels.forEach((model: any) => {
260
            if (this.extensionModels.indexOf(model.fileExt) === -1) {
Alex ORLUC's avatar
Alex ORLUC committed
261
                this.extensionModels.push(model.fileExt);
Vinciane's avatar
Vinciane committed
262
            }
Alex ORLUC's avatar
Alex ORLUC committed
263
        });
264
        this.defaultTemplatesList = data.templatesModels;
Alex ORLUC's avatar
Alex ORLUC committed
265

Vinciane's avatar
Vinciane committed
266
267
        this.attachmentTypesList = data.attachmentTypes;
        this.datasourcesList = data.datasources;
268
269
270
271
        this.maarchTree.initData(data.entities.map(ent => ({
            ...ent,
            id : ent.serialId,
        })));
272
273
    }

274
275
    getBase64Document(buffer: ArrayBuffer) {
        const TYPED_ARRAY = new Uint8Array(buffer);
276
        const STRING_CHAR = TYPED_ARRAY.reduce((data, byte) => data + String.fromCharCode(byte), '');
277
278

        return btoa(STRING_CHAR);
279
280
281
    }

    uploadFileTrigger(fileInput: any) {
282
        if (fileInput.target.files && fileInput.target.files[0] && this.isExtensionAllowed(fileInput.target.files[0])) {
Vinciane's avatar
Vinciane committed
283

284
            const reader = new FileReader();
Vinciane's avatar
Vinciane committed
285

286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
            if (this.template.target === 'acknowledgementReceipt') {
                this.template.file.paper = {
                    name: '',
                    type: '',
                    content: ''
                };
                this.template.file.paper.name = fileInput.target.files[0].name;
                this.selectedModelFile = this.template.file.paper.name;
                this.template.file.paper.type = fileInput.target.files[0].type;
                this.template.file.paper.format = this.template.file.paper.name.split('.').pop();
            } else {
                this.template.file = {
                    name: '',
                    type: '',
                    content: ''
                };
                this.template.file.name = fileInput.target.files[0].name;
                this.selectedModelFile = this.template.file.name;
                this.template.file.type = fileInput.target.files[0].type;
                this.template.file.format = this.template.file.name.split('.').pop();
            }

            reader.readAsArrayBuffer(fileInput.target.files[0]);

            reader.onload = (value: any) => {
                if (this.template.target === 'acknowledgementReceipt') {
                    this.template.file.paper.content = this.getBase64Document(value.target.result);
                } else {
                    this.template.file.content = this.getBase64Document(value.target.result);
                }

317
                this.documentImported = true;
318
                this.getViewTemplateFile();
319
320
321
322
            };
        }
    }

323
324
    isExtensionAllowed(file: any) {
        const fileExtension = file.name.toLowerCase().split('.').pop();
325

326
        if (this.allowedExtensions.filter(ext => ext.toLowerCase() === fileExtension.toLowerCase()).length === 0) {
327
328
329
330
            this.dialog.open(AlertComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: {
                title: this.translate.instant('lang.notAllowedExtension') + ' !',
                msg: this.translate.instant('lang.file') + ' : <b>' + file.name + '</b>, ' + this.translate.instant('lang.type') + ' : <b>' + file.type + '</b><br/><br/><u>' + this.translate.instant('lang.allowedExtensions') + '</u> : <br/>' + this.allowedExtensions.filter((elem: any, index: any, self: any) => index === self.indexOf(elem)).join(', ')
            } });
331
332
333
334
            return false;
        } else {
            return true;
        }
335
336
    }

337
338
    editFile() {
        const editorOptions: any = {};
339
        editorOptions.docUrl = 'rest/onlyOffice/mergedFile';
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        if (this.creationMode) {
            if (this.template.target !== 'acknowledgementReceipt') {
                if (!this.functionsService.empty(this.template.file.content)) {
                    editorOptions.objectType = 'encodedResource';
                    editorOptions.objectId = this.template.file.content;
                    editorOptions.extension = this.template.file.format;
                } else {
                    editorOptions.objectType = 'templateCreation';
                    for (const element of this.defaultTemplatesList) {
                        if (this.selectedModelFile === element.fileExt + ': ' + element.fileName) {
                            editorOptions.objectId = element.filePath;
                        }
                    }
                    editorOptions.extension = editorOptions.objectId.toLowerCase().split('.').pop();
                }
            } else if (this.template.target === 'acknowledgementReceipt') {
                if (!this.functionsService.empty(this.template.file.paper.content)) {
                    editorOptions.objectType = 'encodedResource';
                    editorOptions.objectId = this.template.file.paper.content;
                    editorOptions.extension = this.template.file.paper.format;
                } else {
                    editorOptions.objectType = 'templateCreation';
                    for (const element of this.defaultTemplatesList) {
                        if (this.selectedModelFile === element.fileExt + ': ' + element.fileName) {
                            editorOptions.objectId = element.filePath;
                        }
                    }
                    editorOptions.extension = editorOptions.objectId.toLowerCase().split('.').pop();
368
369
370
                }
            }
        } else {
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
            if (this.template.target !== 'acknowledgementReceipt') {
                if (!this.functionsService.empty(this.template.file.content)) {
                    editorOptions.objectType = 'encodedResource';
                    editorOptions.objectId = this.template.file.content;
                    editorOptions.extension = this.template.file.format;
                } else {
                    editorOptions.objectType = 'templateModification';
                    editorOptions.objectId = this.template.id;
                    editorOptions.extension = this.template.file.name.toLowerCase().split('.').pop();
                }
            } else if (this.template.target === 'acknowledgementReceipt') {
                if (!this.functionsService.empty(this.template.file.paper.content)) {
                    editorOptions.objectType = 'encodedResource';
                    editorOptions.objectId = this.template.file.paper.content;
                    editorOptions.extension = this.template.file.paper.format;
                } else {
                    editorOptions.objectType = 'templateModification';
                    editorOptions.objectId = this.template.id;
                    editorOptions.extension = this.template.file.paper.name.toLowerCase().split('.').pop();
                }
            }
392
393
394
        }

        if (this.headerService.user.preferences.documentEdition === 'java') {
395
            // WORKAROUND JAVA MODE DOESNT SUPPORT BASE64
396
397
398
399
400
401
402
403
404
            if (this.creationMode) {
                editorOptions.objectId = '';
                editorOptions.objectType = 'templateCreation';
                for (const element of this.defaultTemplatesList) {
                    if (this.selectedModelFile === element.fileExt + ': ' + element.fileName) {
                        editorOptions.objectId = element.filePath;
                    }
                }
                if (this.functionsService.empty(editorOptions.objectId)) {
405
                    alert(this.translate.instant('lang.canNotEditImportedDocumentWhenJava'));
406
407
408
409
410
411
                    return false;
                }
            } else {
                editorOptions.objectType = 'templateModification';
                editorOptions.objectId = this.template.id;
            }
412
            editorOptions.authToken = this.authService.getToken();
413
            this.launchJavaEditor(editorOptions);
414
415
        } else if (this.headerService.user.preferences.documentEdition !== 'java') {
            this.launchIntegratedEditor(editorOptions, this.headerService.user.preferences.documentEdition);
416
        }
417
418
419
    }

    launchJavaEditor(params: any) {
420
        this.http.post('../rest/jnlp', params).pipe(
421
            tap((data: any) => {
422
                window.location.href = '../rest/jnlp/' + data.generatedJnlp;
423
424
425
426
427
428
429
430
431
                this.checkLockFile(data.jnlpUniqueId, params.extension);
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

432
    launchIntegratedEditor(params: any, editor: string) {
433
434
435
436
437
438
439
440
441
442
        this.dialogRef = this.dialog.open(
            TemplateFileEditorModalComponent,
            {
                autoFocus: false,
                panelClass: 'maarch-full-height-modal',
                minWidth: '80%',
                disableClose: true,
                data: {
                    title: this.template.template_style,
                    editorOptions: params,
443
444
                    file: { format: params.extension },
                    editorType: editor
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
                }
            }
        );
        this.dialogRef.afterClosed().pipe(
            filter((data: string) => !this.functionsService.empty(data)),
            tap((data: any) => {
                if (this.template.target === 'acknowledgementReceipt') {
                    this.template.file.paper.name = this.selectedModelFile;
                    this.template.file.paper.format = params.extension;
                    this.template.file.paper.content = data.content;
                } else {
                    this.template.file.name = this.selectedModelFile;
                    this.template.file.format = params.extension;
                    this.template.file.content = data.content;
                }
                this.getViewTemplateFile();
            }),
            catchError((err: any) => {
                this.notify.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    getViewTemplateFile() {
470
        this.http.post('../rest/convertedFile/encodedFile', { encodedFile: this.template.target === 'acknowledgementReceipt' ? this.template.file.paper.content : this.template.file.content, format: this.template.target === 'acknowledgementReceipt' ? this.template.file.paper.format : this.template.file.format }).pipe(
471
472
473
474
475
476
477
478
            tap((data: any) => {
                this.templateDocView = this.sanitizer.bypassSecurityTrustResourceUrl('data:application/pdf;base64,' + data.encodedResource);
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
479
480
    }

481
    checkLockFile(id: string, extension: string) {
482
        this.intervalLockFile = setInterval(() => {
483
            this.http.get('../rest/jnlp/lock/' + id).pipe(
484
                tap((data: any) => {
Vinciane's avatar
Vinciane committed
485
486
487
                    this.lockFound = data.lockFileFound;
                    if (!this.lockFound) {
                        clearInterval(this.intervalLockFile);
488
                        this.loadTmpFile(`${data.fileTrunk}.${extension}`);
Vinciane's avatar
Vinciane committed
489
                    }
490
491
                })
            ).subscribe();
492
        }, 1000);
493
494
    }

495
    loadTmpFile(filenameOnTmp: string) {
496
        this.http.get(`../rest/convertedFile/${filenameOnTmp}?convert=true`).pipe(
497
498
499
500
501
502
503
504
505
506
            tap((data: any) => {
                if (this.template.target === 'acknowledgementReceipt') {
                    this.template.file.paper.name = this.selectedModelFile;
                    this.template.file.paper.format = filenameOnTmp.toLowerCase().split('.').pop();
                    this.template.file.paper.content = data.encodedResource;
                } else {
                    this.template.file.name = this.selectedModelFile;
                    this.template.file.format = filenameOnTmp.toLowerCase().split('.').pop();
                    this.template.file.content = data.encodedResource;
                }
507
                this.templateDocView = this.sanitizer.bypassSecurityTrustResourceUrl('data:application/pdf;base64,' + data.encodedConvertedResource);
508
509
510
511
            })
        ).subscribe();
    }

Damien's avatar
Damien committed
512
    duplicateTemplate() {
513
        if (!this.lockFound && this.template.target !== 'acknowledgementReceipt') {
514
515
516
517
518
519
520
521
522
            const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.duplicate')} « ${this.template.label} »`, msg: this.translate.instant('lang.confirmAction') } });
            dialogRef.afterClosed().pipe(
                filter((data: string) => data === 'ok'),
                exhaustMap(() => this.http.post('../rest/templates/' + this.template.id + '/duplicate', { 'id': this.template.id })),
                tap((data: any) => {
                    this.notify.success(this.translate.instant('lang.templateDuplicated'));
                    this.router.navigate(['/administration/templates/' + data.id]);
                }),
                catchError((err: any) => {
523
                    this.notify.handleSoftErrors(err);
524
525
526
                    return of(false);
                })
            ).subscribe();
527
528
529
        }
    }

530
    onSubmit() {
Vinciane's avatar
Vinciane committed
531

532
        /*
533
        if (this.template.type === 'HTML') {
534
            this.template.template_content = tinymce.get('templateHtml').getContent();
Alex ORLUC's avatar
Alex ORLUC committed
535

536
        } else if (this.template.type === 'OFFICE_HTML') {
537
            this.template.template_content = tinymce.get('templateOfficeHtml').getContent();
538
539
540
541
        }*/

        if (this.isValidTemplate()) {
            if (this.creationMode) {
542
                this.http.post('../rest/templates', this.formatTemplate()).pipe(
543
                    tap((data: any) => {
544
545
546
547
548
549
550
551
552
553
554
                        if (data.checkEntities) {
                            this.config = {
                                panelClass: 'maarch-modal',
                                data: {
                                    entitiesList: data.checkEntities,
                                    template_attachment_type: this.template.template_attachment_type
                                }
                            };
                            this.dialog.open(TemplateAdministrationCheckEntitiesModalComponent, this.config);
                        } else {
                            this.router.navigate(['/administration/templates']);
555
                            this.notify.success(this.translate.instant('lang.templateAdded'));
556
                        }
557
558
559
560
561
562
                    }),
                    catchError((err: any) => {
                        this.notify.handleSoftErrors(err);
                        return of(false);
                    })
                ).subscribe();
563
            } else {
564
                this.http.put('../rest/templates/' + this.template.id, this.formatTemplate()).pipe(
565
                    tap((data: any) => {
566
                        if (!this.functionsService.empty(data) && data.checkEntities) {
567
568
569
570
571
572
573
574
575
576
                            this.config = {
                                panelClass: 'maarch-modal',
                                data: {
                                    entitiesList: data.checkEntities,
                                    template_attachment_type: this.template.template_attachment_type
                                }
                            };
                            this.dialogRef = this.dialog.open(TemplateAdministrationCheckEntitiesModalComponent, this.config);
                        } else {
                            this.router.navigate(['/administration/templates']);
577
                            this.notify.success(this.translate.instant('lang.templateUpdated'));
578
                        }
579
580
581
582
583
584
                    }),
                    catchError((err: any) => {
                        this.notify.handleSoftErrors(err);
                        return of(false);
                    })
                ).subscribe();
585
            }
Alex ORLUC's avatar
Alex ORLUC committed
586
        }
Alex ORLUC's avatar
Alex ORLUC committed
587

588
589
590
591
    }

    formatTemplate() {
        const template = { ...this.template };
592
        template.options = {...this.options };
593
        template.entities = this.maarchTree.getSelectedNodes().map(ent => ent.entity_id);
594
        return template;
595
596
597
    }

    isValidTemplate() {
598
        if (this.template.target === 'acknowledgementReceipt' && this.functionsService.empty(this.template.file.paper.name) && this.functionsService.empty(this.template.file.electronic.content)) {
599
            alert(this.translate.instant('lang.mustCompleteAR'));
600
601
602
            return false;

        } else if (this.template.target !== 'acknowledgementReceipt' && this.template.type === 'OFFICE' && this.functionsService.empty(this.template.file.name)) {
603
            alert(this.translate.instant('lang.editModelFirst'));
604
            return false;
605
        } else {
Alex ORLUC's avatar
Alex ORLUC committed
606
607
608
609
            return true;
        }
    }

610
611
612
613
    isVisibleAttachment(id: string) {
        return this.attachmentTypesList.find((attach: any) => attach.id === id)?.visible;
    }

Vinciane's avatar
Vinciane committed
614
    displayDatasources(datasource: any) {
615
        if (datasource.target === 'notification' && this.template.target === 'notifications') {
616
            return true;
617
        } else if (datasource.target === 'document' && this.template.target !== 'notifications') {
618
619
620
621
            return true;
        }
        return false;
    }
622

Damien's avatar
Damien committed
623
    updateTemplateType() {
624
        this.options = {};
625
626
627
628
629
630
631
632
633
634
635
636
637
        this.template.file = {
            name: '',
            type: '',
            content: ''
        };

        this.templateDocView = null;
        if (['attachments', 'indexingFile'].indexOf(this.template.target) > -1) {
            this.template.type = 'OFFICE';
            this.availableTypes = ['OFFICE'];
        } else if (['notifications', 'sendmail'].indexOf(this.template.target) > -1) {
            this.template.type = 'HTML';
            this.availableTypes = ['HTML', 'TXT'];
638
            this.initMce('textarea#templateHtml');
639
640
641
642
        } else if (this.template.target === 'notes') {
            this.template.type = 'TXT';
            this.availableTypes = ['TXT'];
        } else if (this.template.target === 'acknowledgementReceipt') {
643
644
645
            this.options = {
                acknowledgementReceiptFrom : 'destination'
            };
646
647
648
649
650
651
652
653
654
655
656
657
658
659
            this.template.file = {
                electronic: {
                    name: '',
                    type: '',
                    content: ''
                },
                paper: {
                    name: '',
                    type: '',
                    content: ''
                }
            };
            this.template.type = 'OFFICE_HTML';
            this.availableTypes = [];
660
            this.template.template_attachment_type = '';
661
            this.initMce('textarea#templateOfficeHtml');
662
663
        }
    }
664

665
666
667
668
669
670
671
    changeType(ev: any) {
        if (ev.value === 'HTML') {
            this.initMce('textarea#templateHtml');
        } else {
            tinymce.remove('textarea');
        }
        this.template.type = ev.value;
672
    }
Alex ORLUC's avatar
Alex ORLUC committed
673

674
675
676
677
678
679
680
681
682
683
684
685
686
687
    changeModel() {
        this.template.file = {
            name: '',
            type: '',
            content: ''
        };

        this.template.file = {
            electronic: {
                name: '',
                type: '',
                content: ''
            }
        };
688
689

        this.documentImported = false;
690
691
    }

Vinciane's avatar
Vinciane committed
692
    loadTab(event: any) {
Alex ORLUC's avatar
Alex ORLUC committed
693
694
695
        if (event.index === 0) {
            this.initMce('textarea#templateOfficeHtml');
        } else {
696
            tinymce.remove('textarea');
Alex ORLUC's avatar
Alex ORLUC committed
697
            if (this.template.template_file_name == null && this.template.template_style == null) {
698
                this.buttonFileName = this.translate.instant('lang.importFile');
Alex ORLUC's avatar
Alex ORLUC committed
699
700
701
            }
        }
    }
702

703
704
705
706
707
708
709
    setOption(id: string, value: string, reset: boolean = false) {
        if (reset) {
            this.options = {};
        }
        this.options[id] = value;
    }

710
711
    ngOnDestroy() {
        tinymce.remove('textarea');
712
713
714
        if (this.intervalLockFile) {
            clearInterval(this.intervalLockFile);
        }
715
    }
Alex ORLUC's avatar
Alex ORLUC committed
716
}
717
@Component({
718
    templateUrl: 'template-administration-checkEntities-modal.component.html',
719
720
721
    styleUrls: ['template-administration-checkEntities-modal.scss']
})
export class TemplateAdministrationCheckEntitiesModalComponent {
722

Vinciane's avatar
Vinciane committed
723

724
725
    constructor(public http: HttpClient, @Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<TemplateAdministrationCheckEntitiesModalComponent>) {
    }
Damien's avatar
Damien committed
726
}