entities-administration.component.ts 40.5 KB
Newer Older
1
import { Component, OnInit, ViewChild, Inject, TemplateRef, ViewContainerRef } from '@angular/core';
2
import { HttpClient } from '@angular/common/http';
3
import { TranslateService } from '@ngx-translate/core';
4
5
6
7
8
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSidenav } from '@angular/material/sidenav';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
9
10
import { NotificationService } from '@service/notification/notification.service';
import { HeaderService } from '@service/header.service';
Vinciane's avatar
Vinciane committed
11
import { Router } from '@angular/router';
12
import { AppService } from '@service/app.service';
13
import { DiffusionsListComponent } from '../../diffusions/diffusions-list.component';
14
import { tap, catchError, filter, exhaustMap, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
15
import { FunctionsService } from '@service/functions.service';
16
import { ConfirmComponent } from '../../../plugins/modal/confirm.component';
17
18
import { VisaWorkflowComponent } from '../../visa/visa-workflow.component';
import { AvisWorkflowComponent } from '../../avis/avis-workflow.component';
19
import { Observable, of } from 'rxjs';
20
import { EntitiesExportComponent } from './export/entities-export.component';
21
import { FormControl } from '@angular/forms';
22
import { InputCorrespondentGroupComponent } from '../contact/group/inputCorrespondent/input-correspondent-group.component';
23

24
declare let $: any;
25
@Component({
26
    templateUrl: 'entities-administration.component.html',
27
    styleUrls: ['entities-administration.component.scss']
28
})
29
export class EntitiesAdministrationComponent implements OnInit {
30
    @ViewChild('snav2', { static: true }) public sidenavRight: MatSidenav;
31
    @ViewChild('adminMenuTemplate', { static: true }) adminMenuTemplate: TemplateRef<any>;
32
    @ViewChild('appInputCorrespondentGroup', { static: false }) appInputCorrespondentGroup: InputCorrespondentGroupComponent;
33
34
35
36
37
38
39
40
41
42
    @ViewChild('paginatorUsers', { static: false }) paginatorUsers: MatPaginator;
    @ViewChild('paginatorTemplates', { static: false }) paginatorTemplates: MatPaginator;
    @ViewChild('tableUsers', { static: false }) sortUsers: MatSort;
    @ViewChild('tableTemplates', { static: false }) sortTemplates: MatSort;
    @ViewChild('appDiffusionsList', { static: false }) appDiffusionsList: DiffusionsListComponent;
    @ViewChild('appVisaWorkflow', { static: false }) appVisaWorkflow: VisaWorkflowComponent;
    @ViewChild('appAvisWorkflow', { static: false }) appAvisWorkflow: AvisWorkflowComponent;

    /* HEADER*/
    titleHeader: string;
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

    dialogRef: MatDialogRef<any>;

    loading: boolean = false;

    entities: any[] = [];
    listTemplateRoles: any[] = [];
    entityTypeList: any[] = [];
    currentEntity: any = {};
    isDraggable: boolean = true;
    newEntity: boolean = false;
    creationMode: boolean = false;
    visaCircuitModified: boolean = false;
    opinionCircuitModified: boolean = false;
    idVisaCircuit: number;
    idOpinionCircuit: number;
    config: any = {};
60
    emptyField: boolean = true;
61
62
63
64
65

    dataSourceUsers = new MatTableDataSource(this.currentEntity.users);
    dataSourceTemplates = new MatTableDataSource(this.currentEntity.templates);
    displayedColumnsUsers = ['firstname', 'lastname'];
    displayedColumnsTemplates = ['template_label', 'template_target'];
66

67
68
69
70
71
72
73
74
    addressBANInfo: string = '';
    addressBANMode: boolean = true;
    addressBANControl = new FormControl();
    addressBANLoading: boolean = false;
    addressBANResult: any[] = [];
    addressBANFilteredResult: Observable<string[]>;
    addressBANCurrentDepartment: string = '75';
    departmentList: any[] = [];
75
    externalSignatoryBook: string;
76

77
78
79
80
81
82
83
84
85
86
87
    constructor(
        public translate: TranslateService,
        public http: HttpClient,
        private notify: NotificationService,
        public dialog: MatDialog,
        private headerService: HeaderService,
        private router: Router,
        public appService: AppService,
        public functions: FunctionsService,
        private viewContainerRef: ViewContainerRef
    ) { }
88

89
    applyFilterUsers(filterValue: string) {
90
91
        filterValue = filterValue.trim();
        filterValue = filterValue.toLowerCase();
92
93
94
95
96
97
98
        this.dataSourceUsers.filter = filterValue;
    }

    applyFilterTemplates(filterValue: string) {
        filterValue = filterValue.trim();
        filterValue = filterValue.toLowerCase();
        this.dataSourceTemplates.filter = filterValue;
99
    }
100
101


102
    async ngOnInit(): Promise<void> {
103
        this.headerService.setHeader(this.translate.instant('lang.administration') + ' ' + this.translate.instant('lang.entities'));
104

105
        this.headerService.injectInSideBarLeft(this.adminMenuTemplate, this.viewContainerRef, 'adminMenu');
106

107
108
        this.loading = true;

109
110
111
112
113
114
115
        await this.getEntityTypes();
        await this.getRoles();
        await this.getEntities();

        this.loading = false;

        this.initEntitiesTree();
116
        this.initBanSearch();
117
        this.initAutocompleteAddressBan();
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        this.initSignatoryBook();
    }

    initSignatoryBook() {
        this.http.get('../rest/externalConnectionsEnabled').pipe(
            tap((data: any) => {
                Object.keys(data.connection).filter(connectionId => connectionId !== 'maileva').forEach(connectionId => {
                    this.externalSignatoryBook = connectionId;
                });
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
133
134
135
136
    }

    initEntitiesTree() {
        setTimeout(() => {
137
138
            $('#jstree').jstree({
                'checkbox': {
139
                    'deselect_all': true,
140
                    'three_state': false // no cascade selection
141
142
143
144
145
146
147
148
149
                },
                'core': {
                    force_text: true,
                    'themes': {
                        'name': 'proton',
                        'responsive': true
                    },
                    'multiple': false,
                    'data': this.entities,
150
151
152
                    'check_callback': function (operation: any, node: any, node_parent: any, node_position: any, more: any) {
                        if (operation === 'move_node') {
                            if (node_parent.id === '#') {
153
154
155
156
                                return false;
                            } else if (!node_parent.original.allowed) {
                                return false;
                            } else {
157
158
                                return true;
                            }
159
160
161
                        }
                    }
                },
162
                'dnd': {
163
                    is_draggable: function (nodes: any) {
164
165
                        let i = 0;
                        const j = nodes.length;
166
167
168
                        for (; i < j; i++) {
                            if (!nodes[i].original.allowed) {
                                return false;
169
                            }
170
171
172
173
                        }
                        return true;
                    }
                },
174
                'plugins': ['checkbox', 'search', 'dnd', 'sort']
175
            });
176
177
            $('#jstree').jstree('select_node', this.entities[0]);
            let to: any = false;
178
179
180
            $('#jstree_search').keyup( () => {
                const v: any = $('#jstree_search').val();
                this.emptyField = v === '' ? true : false;
181
182
183
                if (to) {
                    clearTimeout(to);
                }
184
                to = setTimeout(function () {
185
                    $('#jstree').jstree(true).search(v);
186
187
                }, 250);
            });
188
            $('#jstree')
189
190
                // listen for event
                .on('select_node.jstree', (e: any, data: any) => {
191
                    if (this.sidenavRight.opened === false) {
192
193
                        this.sidenavRight.open();
                    }
194
                    if (this.creationMode === true) {
195
196
                        this.currentEntity.parent_entity_id = data.node.id;
                    } else {
197
                        if (this.newEntity === true) {
198
199
200
201
202
203
                            this.loadEntity(this.currentEntity.entity_id);
                            this.newEntity = false;
                        } else {
                            this.loadEntity(data.node.id);
                        }
                    }
204

205
                }).on('deselect_node.jstree', (e: any, data: any) => {
206

207
                    this.sidenavRight.close();
208

209
                }).on('move_node.jstree', (e: any, data: any) => {
210

211
                    if (this.currentEntity.parent_entity_id !== this.currentEntity.entity_id) {
212
213
214
215
216
217
218
                        this.currentEntity.parent_entity_id = data.parent;
                    }
                    this.moveEntity();
                })
                // create the instance
                .jstree();

219
220
221
            $(document).on('dnd_start.vakata', (e: any, data: any) => {
                $('#jstree').jstree('deselect_all');
                $('#jstree').jstree('select_node', data.data.nodes[0]);
222
            });
223
224
225
226
227
        }, 0);
    }

    getEntityTypes() {
        return new Promise((resolve, reject) => {
228
            this.http.get('../rest/entityTypes').pipe(
229
230
231
232
233
234
235
236
237
238
239
240
241
242
                tap((data: any) => {
                    this.entityTypeList = data['types'];
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }

    getRoles() {
        return new Promise((resolve, reject) => {
243
            this.http.get('../rest/listTemplates/types/entity_id/roles').pipe(
244
245
246
247
248
249
250
251
252
253
                tap((data: any) => {
                    this.listTemplateRoles = data['roles'];
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
254

255
256
257
258
    }

    getEntities() {
        return new Promise((resolve, reject) => {
259
            this.http.get('../rest/entities').pipe(
260
261
262
263
264
265
266
267
268
269
                tap((data: any) => {
                    this.entities = data['entities'];
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
270

271
272
    }

273
    loadEntity(entity_id: any) {
274
275
        this.visaCircuitModified = false;
        this.opinionCircuitModified = false;
276
        this.http.get('../rest/entities/' + entity_id + '/details')
277
278
            .subscribe((data: any) => {
                this.currentEntity = data['entity'];
279
                this.appInputCorrespondentGroup.ngOnInit();
280
                this.appDiffusionsList.loadListModel(this.currentEntity.id);
281
282
                this.appVisaWorkflow.loadListModel(this.currentEntity.id);
                this.appAvisWorkflow.loadListModel(this.currentEntity.id);
283

284
285
                if (this.currentEntity.visaCircuit) {
                    this.idVisaCircuit = this.currentEntity.visaCircuit.id;
286
                } else {
287
288
289
290
291
292
                    this.idVisaCircuit = null;
                }
                if (this.currentEntity.opinionCircuit) {
                    this.idOpinionCircuit = this.currentEntity.opinionCircuit.id;
                } else {
                    this.idOpinionCircuit = null;
293
                }
294
295
296
297
298
299
300
301
                this.dataSourceUsers = new MatTableDataSource(this.currentEntity.users);
                this.dataSourceUsers.paginator = this.paginatorUsers;
                this.dataSourceUsers.sort = this.sortUsers;

                this.dataSourceTemplates = new MatTableDataSource(this.currentEntity.templates);
                this.dataSourceTemplates.paginator = this.paginatorTemplates;
                this.dataSourceTemplates.sort = this.sortTemplates;

302
303
304
305
306
307
308
309
                if (!this.currentEntity.listTemplate.items) {
                    this.currentEntity.listTemplate.items = [];
                }
                this.listTemplateRoles.forEach((role: any) => {
                    if (role.available && !this.currentEntity.listTemplate.items[role.id]) {
                        this.currentEntity.listTemplate.items[role.id] = [];
                    }
                });
310
311
312
313
314
            }, (err) => {
                this.notify.error(err.error.errors);
            });
    }

315
    addElemListModelVisa(element: any) {
316
        this.visaCircuitModified = true;
317
318
319
320
321
322
        const newElemListModel = {
            'id': element.id,
            'type': 'user',
            'mode': 'sign',
            'idToDisplay': element.idToDisplay,
            'descriptionToDisplay': element.otherInfo
323
324
325
326
327
328
329
        };

        if (!this.currentEntity.visaCircuit.items) {
            this.currentEntity.visaCircuit.items = [];
        }
        this.currentEntity.visaCircuit.items.push(newElemListModel);
        if (this.currentEntity.visaCircuit.items.length > 1) {
330
            this.currentEntity.visaCircuit.items[this.currentEntity.visaCircuit.items.length - 2].mode = 'visa';
331
332
333
334
335
        }
    }

    addElemListModelOpinion(element: any) {
        this.opinionCircuitModified = true;
336
337
338
339
340
341
        const newElemListModel = {
            'id': element.id,
            'type': 'user',
            'mode': 'avis',
            'idToDisplay': element.idToDisplay,
            'descriptionToDisplay': element.otherInfo
342
343
        };

344
345
        if (!this.currentEntity.opinionCircuit.items) {
            this.currentEntity.opinionCircuit.items = [];
346
        }
347
        this.currentEntity.opinionCircuit.items.push(newElemListModel);
348
349
350
    }

    saveEntity() {
351
        if (this.currentEntity.parent_entity_id === '#') {
352
353
            this.currentEntity.parent_entity_id = '';
        }
354
        if (this.currentEntity.parent_entity_id === '' || this.functions.empty(this.currentEntity.parent_entity_id)) {
355
356
357
358
359
360
361
362
            const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.createNewEntity')}`, msg: this.translate.instant('lang.entityWithoutParentMessage') } });
            dialogRef.afterClosed().subscribe((response: any) => {
                if (response) {
                    this.saveEntityBody();
                }
            });
        } else {
            this.saveEntityBody();
Damien's avatar
Damien committed
363
        }
364
    }
Damien's avatar
Damien committed
365

366
367
368
369
    saveEntityBody() {
        if (this.creationMode) {
            if (this.functions.empty(this.currentEntity.producerService)) {
                this.currentEntity.producerService = this.currentEntity.entity_id;
Damien's avatar
Damien committed
370
            }
371
372
            this.http.post('../rest/entities', this.currentEntity).pipe(
                tap((data: any) => {
373
374
375
376
377
378
379
380
381
382
383
384
385
                    this.appInputCorrespondentGroup.linkGrpAfterCreation(data.id, 'entity');
                    this.currentEntity.listTemplate = [];
                    this.entities = data['entities'];
                    this.creationMode = false;
                    this.newEntity = true;
                    $('#jstree').jstree(true).settings.core.data = this.entities;
                    // $('#jstree').jstree(true).settings.select_node = this.currentEntity;
                    $('#jstree').jstree(true).refresh();
                    $('#jstree').on('refresh.jstree', (e: any) => {
                        $('#jstree').jstree('deselect_all');
                        $('#jstree').jstree('select_node', this.currentEntity.entity_id);
                    });
                    this.notify.success(this.translate.instant('lang.entityAdded'));
386
387
388
389
390
391
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
392
        } else {
393
394
            this.http.put('../rest/entities/' + this.currentEntity.entity_id, this.currentEntity).pipe(
                tap((data: any) => {
395
396
397
398
                    this.entities = data['entities'];
                    $('#jstree').jstree(true).settings.core.data = this.entities;
                    $('#jstree').jstree('refresh');
                    this.notify.success(this.translate.instant('lang.entityUpdated'));
399
400
401
402
403
404
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
405
406
407
408
        }
    }

    moveEntity() {
409
        this.http.put('../rest/entities/' + this.currentEntity.entity_id, this.currentEntity)
410
            .subscribe(() => {
411
                this.notify.success(this.translate.instant('lang.entityUpdated'));
412
413
414
            }, (err) => {
                this.notify.error(err.error.errors);
            });
415
416
417
418
    }

    readMode() {
        this.creationMode = false;
419
        this.isDraggable = true;
420
        $('#jstree').jstree('deselect_all');
421
        if (this.currentEntity.parent_entity_id) {
422
            for (let i = 0; i < this.entities.length; i++) {
423
424
                if (this.entities[i].entity_id === this.currentEntity.parent_entity_id) {
                    $('#jstree').jstree('select_node', this.entities[i]);
425
426
                    break;
                }
427
            }
428
        } else {
429
            this.sidenavRight.close();
430
        }
431
432
    }

433
    selectParentEntity(entity_id: any) {
434
        if (this.creationMode) {
435
436
            $('#jstree').jstree('deselect_all');
            $('#jstree').jstree('select_node', entity_id);
437
        }
438
439
    }

440
    removeEntity() {
441
        if (this.currentEntity.documents > 0 || this.currentEntity.redirects > 0 || this.currentEntity.instances > 0 || this.currentEntity.users.length > 0 || this.currentEntity.templates.length > 0) {
442
            this.config = { panelClass: 'maarch-modal', data: { entity: this.currentEntity } };
443
444
445
            this.dialogRef = this.dialog.open(EntitiesAdministrationRedirectModalComponent, this.config);
            this.dialogRef.afterClosed().subscribe((result: any) => {
                if (result) {
446
                    if (this.currentEntity.listTemplate.id) {
447
448
                        this.http.delete('../rest/listTemplates/' + this.currentEntity.listTemplate.id).pipe(
                            tap((data: any) => {
449
                                this.currentEntity.listTemplate.id = data.id;
450
451
                                this.http.get('../rest/listTemplates/types/entity_id/roles').pipe(
                                    tap((dataTemplates: any) => {
452
                                        this.listTemplateRoles = dataTemplates['roles'];
453
454
455
456
457
458
459
460
461
462
463
464
                                    }),
                                    catchError((err: any) => {
                                        this.notify.handleSoftErrors(err);
                                        return of(false);
                                    })
                                ).subscribe();
                            }),
                            catchError((err: any) => {
                                this.notify.handleSoftErrors(err);
                                return of(false);
                            })
                        ).subscribe();
465
                    }
466

467
                    if (this.idVisaCircuit) {
468
                        this.http.delete('../rest/listTemplates/' + this.idVisaCircuit)
469
                            .subscribe(() => {
470
                                this.idVisaCircuit = null;
471
                            }, (err) => {
472
                                this.notify.handleSoftErrors(err);
473
474
                            });
                    }
475

476
                    this.http.put('../rest/entities/' + result.entity_id + '/reassign/' + result.redirectEntity, {})
477
478
                        .subscribe((data: any) => {
                            this.entities = data['entities'];
479
480
                            $('#jstree').jstree(true).settings.core.data = this.entities;
                            $('#jstree').jstree('refresh');
481
                            this.sidenavRight.close();
482

483
                            if (typeof data['deleted'] !== 'undefined' && !data['deleted']) {
484
                                this.notify.success(this.translate.instant('lang.entityDeletedButAnnuaryUnreachable'));
Damien's avatar
Damien committed
485
                            } else {
486
                                this.notify.success(this.translate.instant('lang.entityDeleted'));
Damien's avatar
Damien committed
487
                            }
488
                        }, (err) => {
489
                            this.notify.handleSoftErrors(err);
490
491
492
                        });
                }
                this.dialogRef = null;
493
            });
494
        } else {
495
            const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.delete')} « ${this.currentEntity.entity_label} »`, msg: this.translate.instant('lang.confirmAction') } });
496
497
498
            dialogRef.afterClosed().pipe(
                filter((response: string) => response === 'ok'),
                tap(() => {
499
                    if (this.currentEntity.listTemplate.id) {
500
501
                        this.http.delete('../rest/listTemplates/' + this.currentEntity.listTemplate.id).pipe(
                            tap((data: any) => {
502
                                this.currentEntity.listTemplate.id = data.id;
503
504
                                this.http.get('../rest/listTemplates/types/entity_id/roles').pipe(
                                    tap((dataTemplates: any) => {
505
                                        this.listTemplateRoles = dataTemplates['roles'];
506
507
508
509
510
511
512
513
514
515
516
517
                                    }),
                                    catchError((err: any) => {
                                        this.notify.handleSoftErrors(err);
                                        return of(false);
                                    })
                                ).subscribe();
                            }),
                            catchError((err: any) => {
                                this.notify.handleSoftErrors(err);
                                return of(false);
                            })
                        ).subscribe();
518
519
                    }
                    if (this.idVisaCircuit) {
520
521
                        this.http.delete('../rest/listTemplates/' + this.idVisaCircuit).pipe(
                            tap(() => {
522
                                this.idVisaCircuit = null;
523
524
525
526
527
528
                            }),
                            catchError((err: any) => {
                                this.notify.handleSoftErrors(err);
                                return of(false);
                            })
                        ).subscribe();
529
530
                    }
                    this.http.delete('../rest/entities/' + this.currentEntity.entity_id)
531
                        .subscribe((data: any) => {
532
533
534
535
536
537
538
539
540
541
                            this.entities = data['entities'];
                            $('#jstree').jstree(true).settings.core.data = this.entities;
                            $('#jstree').jstree('refresh');
                            this.sidenavRight.close();
                            if (typeof data['deleted'] !== 'undefined' && !data['deleted']) {
                                this.notify.success(this.translate.instant('lang.entityDeletedButAnnuaryUnreachable'));
                            } else {
                                this.notify.success(this.translate.instant('lang.entityDeleted'));
                            }
                        }, (err: any) => {
542
                            this.notify.handleSoftErrors(err);
543
                        });
544
545
546
547
548
549
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
550
551
        }

552
553
554
555
    }

    prepareEntityAdd() {
        this.creationMode = true;
556
        this.isDraggable = false;
Alex ORLUC's avatar
Alex ORLUC committed
557
558
        if (this.currentEntity.entity_id) {
            for (let i = 0; i < this.entities.length; i++) {
559
560
                if (this.entities[i].entity_id === this.currentEntity.entity_id) {
                    this.currentEntity = { 'entity_type': this.entityTypeList[0].id };
Alex ORLUC's avatar
Alex ORLUC committed
561
562
563
564
565
                    this.currentEntity.parent_entity_id = this.entities[i].entity_id;
                    break;
                }
            }
        } else {
566
567
            this.currentEntity = { 'entity_type': this.entityTypeList[0].id };
            $('#jstree').jstree('deselect_all');
568
            this.sidenavRight.open();
569
            /* for (let i = 0; i < this.entities.length; i++) {
Alex ORLUC's avatar
Alex ORLUC committed
570
                if (this.entities[i].allowed == true) {
571
                    $('#jstree').jstree('select_node', this.entities[i]);
Alex ORLUC's avatar
Alex ORLUC committed
572
573
                    break;
                }
574
            }*/
575
        }
576
577
    }

578
    updateStatus(entity: any, method: string) {
579
        this.http.put('../rest/entities/' + entity['entity_id'] + '/status', { 'method': method })
580
            .subscribe((data: any) => {
581
                this.notify.success('');
582
583
584
585
586
            }, (err) => {
                this.notify.error(err.error.errors);
            });
    }

587
    saveDiffList() {
588
589
590
591
592
        const newDiffList = {
            'title': this.currentEntity.entity_id,
            'description': this.currentEntity.entity_id,
            'type': 'diffusionList',
            'entityId': this.currentEntity.id,
593
594
595
596
597
            'items': this.appDiffusionsList.getCurrentListinstance().map((item: any) => ({
                'id': item.item_id,
                'type': item.item_type,
                'mode': item.item_mode
            }))
598
        };
599

600
        if (!this.functions.empty(this.currentEntity.listTemplate.id)) {
601
            this.http.put(`../rest/listTemplates/${this.currentEntity.listTemplate.id}`, newDiffList).pipe(
602
                tap(() => {
603
                    this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
604
605
606
607
608
609
                    this.appDiffusionsList.loadListModel(this.currentEntity.id);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
610
            ).subscribe();
611
        } else {
612
            this.http.post('../rest/listTemplates?admin=true', newDiffList).pipe(
613
                tap((data: any) => {
614
                    this.currentEntity.listTemplate.id = data.id;
615
                    this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
616
617
618
619
620
621
                    this.appDiffusionsList.loadListModel(this.currentEntity.id);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
622
            ).subscribe();
623
624
        }
    }
625

626
    deleteDiffList() {
627
        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') } });
628
629
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
630
            exhaustMap(() => this.http.delete(`../rest/listTemplates/${this.currentEntity.listTemplate.id}`)),
631
632
            tap(() => {
                this.currentEntity.listTemplate.id = null;
633
                this.notify.success(this.translate.instant('lang.diffusionModelDeleted'));
634
635
636
637
638
639
640
641
642
                this.appDiffusionsList.loadListModel(this.currentEntity.id);
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

643
    saveDiffListVisa() {
644
        const newDiffList = {
645
646
647
648
            'title': this.currentEntity.entity_id,
            'description': this.currentEntity.entity_id,
            'type': 'visaCircuit',
            'entityId': this.currentEntity.id,
649
650
651
652
653
654
            'items': this.appVisaWorkflow.getWorkflow().map((item: any, index: number) => ({
                'id': item.item_id,
                'type': item.item_type,
                'mode': item.requested_signature ? 'sign' : 'visa',
                'sequence': index
            }))
655
        };
656
        if (!this.appVisaWorkflow.isValidWorkflow() && !this.functions.empty(newDiffList.items)) {
657
            this.notify.error(this.appVisaWorkflow.getError());
658
        } else {
659
            if (this.functions.empty(newDiffList.items)) {
660
                this.http.delete(`../rest/listTemplates/${this.idVisaCircuit}`).pipe(
661
662
                    tap(() => {
                        this.idVisaCircuit = null;
663
                        this.notify.success(this.translate.instant('lang.diffusionModelDeleted'));
664
665
666
667
668
669
670
671
                        this.appVisaWorkflow.loadListModel(this.currentEntity.id);
                    }),
                    catchError((err: any) => {
                        this.notify.handleSoftErrors(err);
                        return of(false);
                    })
                ).subscribe();
            } else if (!this.functions.empty(this.idVisaCircuit)) {
672
                this.http.put(`../rest/listTemplates/${this.idVisaCircuit}`, newDiffList).pipe(
673
                    tap(() => {
674
                        this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
675
676
677
678
679
680
681
682
                        this.appVisaWorkflow.loadListModel(this.currentEntity.id);
                    }),
                    catchError((err: any) => {
                        this.notify.handleSoftErrors(err);
                        return of(false);
                    })
                ).subscribe();
            } else {
683
                this.http.post('../rest/listTemplates?admin=true', newDiffList).pipe(
684
685
                    tap((data: any) => {
                        this.idVisaCircuit = data.id;
686
                        this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
687
688
689
690
691
692
693
694
                        this.appVisaWorkflow.loadListModel(this.currentEntity.id);
                    }),
                    catchError((err: any) => {
                        this.notify.handleSoftErrors(err);
                        return of(false);
                    })
                ).subscribe();
            }
695
        }
696
697
    }

698
699
    saveDiffListOpinion() {
        const newDiffList = {
700
701
702
703
            'title': this.currentEntity.entity_id,
            'description': this.currentEntity.entity_id,
            'type': 'opinionCircuit',
            'entityId': this.currentEntity.id,
704
705
706
707
708
709
            'items': this.appAvisWorkflow.getWorkflow().map((item: any, index: number) => ({
                'id': item.item_id,
                'type': item.item_type,
                'mode': 'avis',
                'sequence': index
            }))
710
        };
711
712

        if (this.functions.empty(newDiffList.items)) {
713
            this.http.delete(`../rest/listTemplates/${this.idOpinionCircuit}`).pipe(
714
                tap(() => {
715
                    this.idOpinionCircuit = null;
716
                    this.notify.success(this.translate.instant('lang.diffusionModelDeleted'));
717
718
719
720
721
722
723
724
                    this.appAvisWorkflow.loadListModel(this.currentEntity.id);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        } else if (!this.functions.empty(this.idOpinionCircuit)) {
725
            this.http.put(`../rest/listTemplates/${this.idOpinionCircuit}`, newDiffList).pipe(
726
                tap(() => {
727
                    this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
728
729
730
731
732
733
734
735
                    this.appAvisWorkflow.loadListModel(this.currentEntity.id);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        } else {
736
            this.http.post('../rest/listTemplates?admin=true', newDiffList).pipe(
737
738
                tap((data: any) => {
                    this.idOpinionCircuit = data.id;
739
                    this.notify.success(this.translate.instant('lang.diffusionModelUpdated'));
740
741
742
743
744
745
746
                    this.appAvisWorkflow.loadListModel(this.currentEntity.id);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
747
        }
748
    }
Alex ORLUC's avatar
Alex ORLUC committed
749

750
751
752
753
754
    removeDiffListOpinion(template: any, i: number): any {
        this.opinionCircuitModified = true;
        this.currentEntity.opinionCircuit.items.splice(i, 1);
    }

755
756
    toggleRole(role: any) {
        if (role.usedIn.length > 0) {
757
            const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, data: { title: this.translate.instant('lang.confirmAction'), msg: this.translate.instant('lang.roleUsedInTemplateInfo') + ' : <b>' + role.usedIn.join(', ') + '</b><br/>' + this.translate.instant('lang.roleUsedInTemplateInfo2') } });
758

759
            dialogRef.afterClosed().subscribe(result => {
760
                if (result === 'ok') {
761
                    role.available = !role.available;
762
                    this.http.put('../rest/listTemplates/types/entity_id/roles', { 'roles': this.listTemplateRoles })
763
764
765
                        .subscribe(() => {
                            role.usedIn = [];
                            if (this.currentEntity.listTemplate) {
766
                                this.currentEntity.listTemplate.items[role.id] = [];
767
                            }
768
                            this.notify.success(this.translate.instant('lang.listTemplatesRolesUpdated'));
769
770
771
                        }, (err) => {
                            this.notify.error(err.error.errors);
                        });
772
                }
Alex ORLUC's avatar
Alex ORLUC committed
773
            });
774
775
        } else {
            role.available = !role.available;
776
            this.http.put('../rest/listTemplates/types/entity_id/roles', { 'roles': this.listTemplateRoles })
777
778
                .subscribe(() => {
                    if (this.currentEntity.listTemplate) {
779
                        this.currentEntity.listTemplate.items[role.id] = [];
780
                        this.http.get('../rest/listTemplates/types/entity_id/roles')
781
782
783
784
785
786
                            .subscribe((data: any) => {
                                this.listTemplateRoles = data['roles'];
                            }, (err) => {
                                this.notify.error(err.error.errors);
                            });
                    }
787
                    this.notify.success(this.translate.instant('lang.listTemplatesRolesUpdated'));
788
789
790
791
                }, (err) => {
                    this.notify.error(err.error.errors);
                });
        }
792
    }
793

794
    linkUser(newUser: any) {
795
796
797
        const entity = {
            'entityId': this.currentEntity.entity_id,
            'role': ''
798
        };
799

800
        this.http.post('../rest/users/' + newUser.id + '/entities', entity)
801
            .subscribe((data: any) => {
802
803
                const displayName = newUser.idToDisplay.split(' ');
                const user = {
804
805
806
807
                    id: newUser.id,
                    user_id: newUser.otherInfo,
                    firstname: displayName[0],
                    lastname: displayName[1]
Damien's avatar
Damien committed
808
                };
809
                this.currentEntity.users.push(user);
810
811
812
                this.dataSourceUsers = new MatTableDataSource(this.currentEntity.users);
                this.dataSourceUsers.paginator = this.paginatorUsers;
                this.dataSourceUsers.sort = this.sortUsers;
813
                this.notify.success(this.translate.instant('lang.userAdded'));
814
815
816
            }, (err) => {
                this.notify.error(err.error.errors);
            });
Alex ORLUC's avatar
Alex ORLUC committed
817
    }
Vinciane's avatar
Vinciane committed
818

819
820
    showTemplate(templateId: any) {
        if (this.currentEntity.canAdminTemplates) {
Vinciane's avatar
Vinciane committed
821
822
823
            this.router.navigate(['/administration/templates/' + templateId]);
        }
    }
Damien's avatar
Damien committed
824
825

    addEntityToAnnuary() {
826
        this.http.put('../rest/entities/' + this.currentEntity.id + '/annuaries', this.currentEntity)
Damien's avatar
Damien committed
827
828
            .subscribe((data: any) => {
                this.currentEntity.business_id = data['entitySiret'];
829
                if (typeof data['synchronized'] === 'undefined') {
830
                    this.notify.success(this.translate.instant('lang.siretGenerated'));
Damien's avatar
Damien committed
831
832
                } else {
                    if (data['synchronized']) {
833
                        this.notify.success(this.translate.instant('lang.siretGeneratedAndSynchronizationDone'));
Damien's avatar
Damien committed
834
                    } else {
835
                        this.notify.success(this.translate.instant('lang.siretGeneratedButAnnuaryUnreachable'));
Damien's avatar
Damien committed
836
837
838
839
840
841
                    }
                }
            }, (err: any) => {
                this.notify.handleErrors(err);
            });
    }
842
843

    openExportModal() {
844
        this.dialog.open(EntitiesExportComponent, { panelClass: 'maarch-modal', width: '400px', autoFocus: false });
845
846

    }
847
848
849
850
851
852

    clearFilter() {
        $('#jstree_search').val('');
        $('#jstree').jstree(true).search('');
        this.emptyField = true;
    }
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905

    initBanSearch() {
        this.http.get('../rest/ban/availableDepartments').pipe(
            tap((data: any) => {
                if (data.default !== null && data.departments.indexOf(data.default.toString()) !== - 1) {
                    this.addressBANCurrentDepartment = data.default;
                }
                this.departmentList = data.departments;
            }),
            catchError((err: any) => {
                this.notify.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    initAutocompleteAddressBan() {
        this.addressBANInfo = this.translate.instant('lang.autocompleteInfo');
        this.addressBANResult = [];
        this.addressBANControl.valueChanges
            .pipe(
                debounceTime(300),
                filter(value => value.length > 2),
                distinctUntilChanged(),
                tap(() => this.addressBANLoading = true),
                switchMap((data: any) => this.http.get('../rest/autocomplete/banAddresses', { params: { 'address': data, 'department': this.addressBANCurrentDepartment } })),
                tap((data: any) => {
                    if (data.length === 0) {
                        this.addressBANInfo = this.translate.instant('lang.noAvailableValue');
                    } else {
                        this.addressBANInfo = '';
                    }
                    this.addressBANResult = data;
                    this.addressBANFilteredResult = of(this.addressBANResult);
                    this.addressBANLoading = false;
                })
            ).subscribe();
    }

    resetAutocompleteAddressBan() {
        this.addressBANResult = [];
        this.addressBANInfo = this.translate.instant('lang.autocompleteInfo');
    }

    selectAddressBan(ev: any) {
        this.currentEntity.addressNumber = ev.option.value.number;
        this.currentEntity.addressStreet = ev.option.value.afnorName;
        this.currentEntity.addressPostcode = ev.option.value.postalCode;
        this.currentEntity.addressTown = ev.option.value.city;
        this.currentEntity.addressCountry = 'FRANCE';

        this.addressBANControl.setValue('');
    }
906
907
908
909

    copyAddress() {
        this.http.get(`../rest/entities/${this.currentEntity.id}/parentAddress`).pipe(
            tap((data: any) => {
910
                if (data !== null) {
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
                    this.currentEntity.addressNumber = data.addressNumber;
                    this.currentEntity.addressStreet = data.addressStreet;
                    this.currentEntity.addressPostcode = data.addressPostcode;
                    this.currentEntity.addressTown = data.addressTown;
                    this.currentEntity.addressCountry = data.addressCountry;
                    this.currentEntity.addressAdditional1 = data.addressAdditional1;
                    this.currentEntity.addressAdditional2 = data.addressAdditional2;
                } else {
                    this.notify.error(this.translate.instant('lang.noAddressFound'));
                }
            }),
            catchError((err: any) => {
                this.notify.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }
928
}