contacts-form.component.ts 43.3 KB
Newer Older
1
2
import { Component, OnInit, ViewChild, EventEmitter, Input, Output } from '@angular/core';
import { HttpClient } from '@angular/common/http';
3
import { TranslateService } from '@ngx-translate/core';
4
5
import { NotificationService } from '@service/notification/notification.service';
import { HeaderService } from '@service/header.service';
6
import { MatSidenav } from '@angular/material/sidenav';
7
import { AppService } from '@service/app.service';
8
import { MatDialog } from '@angular/material/dialog';
9
import { switchMap, catchError, filter, exhaustMap, tap, debounceTime, distinctUntilChanged, finalize, map, startWith } from 'rxjs/operators';
10
import { FormControl, Validators, ValidatorFn } from '@angular/forms';
11
import { ActivatedRoute, Router } from '@angular/router';
12
13
import { ContactService } from '@service/contact.service';
import { FunctionsService } from '@service/functions.service';
14
import { trigger, transition, style, animate } from '@angular/animations';
15
import { Observable, of } from 'rxjs';
16
import { environment } from '../../../../../environments/environment';
17
import { LatinisePipe } from 'ngx-pipes';
18
import { InputCorrespondentGroupComponent } from '../../group/inputCorrespondent/input-correspondent-group.component';
19

20
21
@Component({
    selector: 'app-contact-form',
22
    templateUrl: 'contacts-form.component.html',
23
    styleUrls: ['contacts-form.component.scss'],
24
    providers: [ContactService],
25
26
27
28
    animations: [
        trigger('hideShow', [
            transition(
                ':enter', [
29
30
31
                    style({ height: '0px' }),
                    animate('200ms', style({ 'height': '30px' }))
                ]
32
33
34
            ),
            transition(
                ':leave', [
35
36
37
                    style({ height: '30px' }),
                    animate('200ms', style({ 'height': '0px' }))
                ]
38
39
40
            )
        ]),
    ],
41
42
43
44
})
export class ContactsFormComponent implements OnInit {

    @ViewChild('snav2', { static: true }) public sidenavRight: MatSidenav;
45
    @ViewChild('appInputCorrespondentGroup', { static: false }) appInputCorrespondentGroup: InputCorrespondentGroupComponent;
46
47
48

    @Input() creationMode: boolean = true;
    @Input() contactId: number = null;
49
50
    @Input() actionButton: boolean = true;
    @Input() defaultName: string = '';
51
52
53

    @Output() onSubmitEvent = new EventEmitter<number>();

54
55
56
57
58
59
    countries: any = [];
    countriesFilteredResult: Observable<string[]>;
    countryControl = new FormControl();

    loading: boolean = false;

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

62
63
64
    contactUnit = [
        {
            id: 'mainInfo',
65
            label: this.translate.instant('lang.denomination')
66
67
68
        },
        {
            id: 'address',
69
            label: this.translate.instant('lang.address')
70
71
72
        },
        {
            id: 'complement',
73
            label: this.translate.instant('lang.additionals')
74
75
76
77
        },
        {
            id: 'maarch2maarch',
            label: 'Maarch2Maarch'
78
79
80
81
82
83
84
        }
    ];

    contactForm: any[] = [
        {
            id: 'company',
            unit: 'mainInfo',
85
            label: this.translate.instant('lang.contactsParameters_company'),
86
87
88
89
90
91
92
            type: 'string',
            control: new FormControl(),
            required: false,
            display: true,
            filling: false,
            values: []
        },
93
94
95
        {
            id: 'civility',
            unit: 'mainInfo',
96
            label: this.translate.instant('lang.contactsParameters_civility'),
97
98
99
100
101
102
103
            type: 'select',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
104
105
106
        {
            id: 'firstname',
            unit: 'mainInfo',
107
            label: this.translate.instant('lang.contactsParameters_firstname'),
108
109
110
111
112
113
114
115
116
117
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'lastname',
            unit: 'mainInfo',
118
            label: this.translate.instant('lang.contactsParameters_lastname'),
119
120
121
122
123
124
125
126
127
128
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'function',
            unit: 'mainInfo',
129
            label: this.translate.instant('lang.contactsParameters_function'),
130
131
132
133
134
135
136
137
138
139
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'department',
            unit: 'mainInfo',
140
            label: this.translate.instant('lang.contactsParameters_department'),
141
142
143
144
145
146
147
148
149
150
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'email',
            unit: 'mainInfo',
151
            label: this.translate.instant('lang.email'),
152
153
154
155
156
157
158
159
160
161
            type: 'string',
            control: new FormControl(),
            required: false,
            display: true,
            filling: false,
            values: []
        },
        {
            id: 'phone',
            unit: 'mainInfo',
162
            label: this.translate.instant('lang.phoneNumber'),
163
164
165
166
167
168
169
            type: 'string',
            control: new FormControl(),
            required: false,
            display: true,
            filling: false,
            values: []
        },
170
171
172
173
174
175
176
177
178
179
180
        {
            id: 'notes',
            unit: 'mainInfo',
            label: this.translate.instant('lang.note'),
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
181
        {
182
            id: 'addressAdditional1',
183
            unit: 'address',
184
            label: this.translate.instant('lang.contactsParameters_addressAdditional1'),
185
186
187
188
189
190
191
192
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
193
            id: 'addressNumber',
194
            unit: 'address',
195
            label: this.translate.instant('lang.contactsParameters_addressNumber'),
196
197
198
199
200
201
202
203
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
204
            id: 'addressStreet',
205
            unit: 'address',
206
            label: this.translate.instant('lang.contactsParameters_addressStreet'),
207
208
209
210
211
212
213
214
215
216
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'addressAdditional2',
            unit: 'address',
217
            label: this.translate.instant('lang.contactsParameters_addressAdditional2'),
218
219
220
221
222
223
224
225
226
227
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'addressPostcode',
            unit: 'address',
228
            label: this.translate.instant('lang.contactsParameters_addressPostcode'),
229
230
231
232
233
234
235
236
237
238
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'addressTown',
            unit: 'address',
239
            label: this.translate.instant('lang.contactsParameters_addressTown'),
240
241
242
243
244
245
246
247
248
249
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
        },
        {
            id: 'addressCountry',
            unit: 'address',
250
            label: this.translate.instant('lang.contactsParameters_addressCountry'),
251
252
253
254
255
256
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
257
        },
258
259
260
261
262
263
264
265
266
267
268
        {
            id: 'sector',
            unit: 'address',
            label: this.translate.instant('lang.contactsParameters_sector'),
            type: 'string',
            control: new FormControl({value: '', disabled: true}),
            required: false,
            display: true,
            filling: false,
            values: []
        },
269
270
        {
            id: 'communicationMeans',
271
            unit: 'maarch2maarch',
272
273
            label: this.translate.instant('lang.communicationMean'),
            desc: `${this.translate.instant('lang.communicationMeanDesc')} (${this.translate.instant('lang.see')} <a href="${this.maarch2maarchUrl}" target="_blank">MAARCH2MAARCH</a>)`,
274
275
276
277
278
279
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
280
281
        },
        {
282
            id: 'externalId_m2m',
283
            unit: 'maarch2maarch',
284
285
            label: this.translate.instant('lang.IdMaarch2Maarch'),
            desc: `${this.translate.instant('lang.m2mContactInfo')} (${this.translate.instant('lang.see')} <a href="${this.maarch2maarchUrl}" target="_blank">MAARCH2MAARCH</a>)`,
286
287
288
289
290
291
            type: 'string',
            control: new FormControl(),
            required: false,
            display: false,
            filling: false,
            values: []
292
293
294
295
296
297
298
299
300
301
302
303
        },
        {
            id: 'correspondentsGroups',
            unit: 'complement',
            label: this.translate.instant('lang.correspondentsGroups'),
            desc: this.translate.instant('lang.correspondentsGroups'),
            type: 'correspondentsGroups',
            control: new FormControl(),
            required: false,
            display: true,
            filling: false,
            values: []
304
305
        }
    ];
306
    initCorrespondentsGroups: boolean = true;
307
308
309
310
311
312
313
314
315
316
317
318
319

    addressBANInfo: string = '';
    addressBANMode: boolean = true;
    addressBANControl = new FormControl();
    addressBANLoading: boolean = false;
    addressBANResult: any[] = [];
    addressBANFilteredResult: Observable<string[]>;
    addressBANCurrentDepartment: string = '75';
    departmentList: any[] = [];

    fillingParameters: any = null;
    fillingRate: any = {
        class: 'warn',
320
        color: this.contactService.getFillingColor('first'),
321
        value: 0
322
    };
323
324

    companyFound: any = null;
325
326
327
328
329
    communicationMeanInfo: string = '';
    communicationMeanResult: any[] = [];
    communicationMeanLoading: boolean = false;
    communicationMeanFilteredResult: Observable<any[]>;

330
331
332
333
    externalId_m2mInfo: string = '';
    externalId_m2mResult: any[] = [];
    externalId_m2mLoading: boolean = false;
    externalId_m2mFilteredResult: Observable<any[]>;
334
    annuaryM2MId: any = null;
335

336
337
    annuaryEnabled: boolean = false;

338
    constructor(
339
        public translate: TranslateService,
340
341
342
343
344
345
        public http: HttpClient,
        private route: ActivatedRoute,
        private router: Router,
        private notify: NotificationService,
        private headerService: HeaderService,
        public appService: AppService,
346
347
        public dialog: MatDialog,
        private contactService: ContactService,
348
349
        public functions: FunctionsService,
        private latinisePipe: LatinisePipe
350
351
352
353
354
355
356
357
358
359
360
361
    ) { }

    ngOnInit(): void {

        this.loading = true;

        this.initBanSearch();

        if (this.contactId === null) {

            this.creationMode = true;

362
            this.http.get('../rest/contactsParameters').pipe(
363
364
365
                tap((data: any) => {
                    this.fillingParameters = data.contactsFilling;
                    this.initElemForm(data);
366
367
368
                    if (!this.functions.empty(this.defaultName)) {
                        this.contactForm.find(contact => contact.id === 'company').control.setValue(this.defaultName);
                    }
369
                    this.annuaryEnabled = data.annuaryEnabled;
370
                }),
371
                exhaustMap(() => this.http.get('../rest/civilities')),
372
373
374
                tap((data: any) => {
                    this.initCivilities(data.civilities);
                }),
375
                exhaustMap(() => this.http.get('../rest/contactsCustomFields')),
376
377
                tap((data: any) => {
                    this.initCustomElementForm(data);
378
                    this.initAutocompleteAddressBan();
379
380
                    this.initAutocompleteCommunicationMeans();
                    this.initAutocompleteExternalIdM2M();
381
382
                    this.getCountries();
                    this.initAutocompleteCountries();
383
384
385
386
387
388
389
390
391
392
393
                }),
                finalize(() => this.loading = false),
                catchError((err: any) => {
                    this.notify.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        } else {
            this.creationMode = false;

            this.contactForm.forEach(element => {
394
                element.display = element.id === 'correspondentsGroups';
395
396
            });

397
            this.http.get('../rest/contactsParameters').pipe(
398
399
400
                tap((data: any) => {
                    this.fillingParameters = data.contactsFilling;
                    this.initElemForm(data);
401
                    this.annuaryEnabled = data.annuaryEnabled;
402
                }),
403
                exhaustMap(() => this.http.get('../rest/civilities')),
404
405
406
                tap((data: any) => {
                    this.initCivilities(data.civilities);
                }),
407
                exhaustMap(() => this.http.get('../rest/contactsCustomFields')),
408
409
                tap((data: any) => {
                    this.initCustomElementForm(data);
410
                    this.initAutocompleteAddressBan();
411
412
                    this.initAutocompleteCommunicationMeans();
                    this.initAutocompleteExternalIdM2M();
413
414
                    this.getCountries();
                    this.initAutocompleteCountries();
415
                }),
416
                exhaustMap(() => this.http.get('../rest/contacts/' + this.contactId)),
417
                map((data: any) => {
418
                    // data.civility = this.contactService.formatCivilityObject(data.civility);
419
                    data.fillingRate = this.contactService.formatFillingObject(data.fillingRate);
420
421
                    return data;
                }),
422
423
                tap((data) => {
                    this.setContactData(data);
424
                    this.setContactDataExternal(data);
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
                }),
                filter((data: any) => data.customFields !== null),
                tap((data: any) => {
                    this.setContactCustomData(data);
                }),
                finalize(() => this.loading = false),
                catchError((err: any) => {
                    this.notify.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
        }
    }

    initElemForm(data: any) {
        let valArr: ValidatorFn[] = [];

        data.contactsParameters.forEach((element: any) => {
443
444
            let targetField: any = this.contactForm.filter(contact => contact.id === element.identifier)[0];

445
446
            valArr = [];

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
            if (targetField === undefined && element.identifier.split('_')[1] !== undefined) {
                let field: any = {};

                field = {
                    id: `customField_${element.identifier.split('_')[1]}`,
                    unit: 'complement',
                    label: null,
                    type: null,
                    control: new FormControl(),
                    required: false,
                    display: false,
                    values: []
                };
                this.contactForm.push(field);

                targetField = this.contactForm.filter(contact => contact.id === field.id)[0];
463
            }
464
            if (targetField !== undefined) {
465

466
                if ((element.filling && this.fillingParameters.enable && this.creationMode) || element.mandatory) {
467
468
                    targetField.display = true;
                }
469

470
                if (element.filling && this.fillingParameters.enable) {
471
472
                    targetField.filling = true;
                }
473

474
475
476
                if (element.identifier === 'email') {
                    valArr.push(Validators.email);
                } else if (element.identifier === 'phone') {
477
                    valArr.push(Validators.pattern(/^\+?((|\ |\.|\(|\)|\-)?(\d)*)*\d$/));
478
                }
479

480
481
482
483
                if (element.mandatory) {
                    targetField.required = true;
                    valArr.push(Validators.required);
                }
484

485
                targetField.control.setValidators(valArr);
486
487
488
489
            }
        });
    }

490
    initCivilities(civilities: any) {
491
        this.contactForm.filter(contact => contact.id === 'civility')[0].values = civilities;
492
493
    }

494
    getCountries() {
495
        this.http.get('../rest/registeredMail/countries').pipe(
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
            tap((data: any) => {
                this.countries = data.countries.map(
                    (item: any) => this.latinisePipe.transform(item.toUpperCase()));
            }),
            catchError((err: any) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    initAutocompleteCountries() {
        this.contactForm.map((field: any) => {
            if (field.id === 'addressCountry') {
                this.countriesFilteredResult = field.control.valueChanges
511
512
513
514
                    .pipe(
                        startWith(''),
                        map((value: any) => this._filter(value))
                    );
515
516
517
518
519
520
521
522
523
            }
        });
    }

    selectCountry(ev: any) {
        const indexFieldAddressCountry = this.contactForm.map(field => field.id).indexOf('addressCountry');
        this.contactForm[indexFieldAddressCountry].control.setValue(ev.option.value);
    }

524
525
526
527
528
529
530
    initCustomElementForm(data: any) {
        let valArr: ValidatorFn[] = [];

        let field: any = {};

        data.customFields.forEach((element: any) => {
            valArr = [];
531
            field = this.contactForm.filter(contact => contact.id === 'customField_' + element.id)[0];
532

533
            if (field !== undefined) {
534
535
                field.label = element.label;
                field.type = element.type;
536
                field.values = element.values.map((value: any) => ({ id: value, label: value }));
537
538
539
540
                if (element.type === 'integer') {
                    valArr.push(Validators.pattern(/^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$/));
                    field.control.setValidators(valArr);
                }
541
542
543
544
545
546
            }
        });
    }

    setContactData(data: any) {
        let indexField = -1;
547

548
549
        Object.keys(data).forEach(element => {
            indexField = this.contactForm.map(field => field.id).indexOf(element);
550

551
            if (!this.isEmptyValue(data[element]) && indexField > -1) {
552
                if (element === 'civility') {
553
554
555
556
557
                    this.contactForm[indexField].control.setValue(data[element].id);
                } else {
                    this.contactForm[indexField].control.setValue(data[element]);
                }

558
                if (element === 'company' && this.isEmptyValue(this.contactForm.filter(contact => contact.id === 'lastname')[0].control.value)) {
559
                    this.contactForm.filter(contact => contact.id === 'lastname')[0].display = false;
560
                } else if (element === 'lastname' && this.isEmptyValue(this.contactForm.filter(contact => contact.id === 'company')[0].control.value)) {
561
562
                    this.contactForm.filter(contact => contact.id === 'company')[0].display = false;
                }
563

564
565
566
                this.contactForm[indexField].display = true;
            }
        });
567
568
569
570
571

        if (this.isEmptyValue(this.contactForm.filter(contact => contact.id === 'company')[0].control.value) && !this.isEmptyValue(this.contactForm.filter(contact => contact.id === 'lastname')[0].control.value)) {
            this.contactForm.filter(contact => contact.id === 'company')[0].display = false;
        }

572
573
574
        this.checkFilling();
    }

575
576
577
578
    setContactDataExternal(data: any) {

        if (data.externalId !== undefined) {
            Object.keys(data.externalId).forEach(id => {
579

580
                if (!this.isEmptyValue(data.externalId[id])) {
581
582
583
                    if (id === 'm2m') {
                        this.contactForm.filter(contact => contact.id === 'externalId_m2m')[0].control.setValue(data.externalId[id]);
                        this.contactForm.filter(contact => contact.id === 'externalId_m2m')[0].display = true;
584
                    } else if (id === 'm2m_annuary_id') {
585
586
                        this.contactForm.push({
                            id: `externalId_${id}`,
587
                            unit: 'maarch2maarch',
588
589
590
591
592
593
594
595
                            label: id,
                            type: 'string',
                            control: new FormControl({ value: data.externalId[id], disabled: true }),
                            required: false,
                            display: true,
                            filling: false,
                            values: []
                        });
596
597
598
599
600
601
602
603
604
605
606
607
608
                    } else {
                        this.contactForm.push({
                            id: `externalId_${id}`,
                            unit: 'complement',
                            label: id,
                            type: 'string',
                            control: new FormControl({ value: data.externalId[id], disabled: true }),
                            required: false,
                            display: true,
                            filling: false,
                            values: []
                        });

609
610
611
                    }
                }
            });
612
        }
613
614
    }

615
616
617
618
    setContactCustomData(data: any) {
        let indexField = -1;
        Object.keys(data.customFields).forEach(element => {
            indexField = this.contactForm.map(field => field.id).indexOf('customField_' + element);
619
            if (!this.isEmptyValue(data.customFields[element]) && indexField > -1) {
620
621
622
623
                if (this.contactForm[indexField].type === 'date') {
                    const date = new Date(this.functions.formatFrenchDateToTechnicalDate(data.customFields[element]));
                    data.customFields[element] = date;
                }
624
625
626
627
628
629
630
631
                this.contactForm[indexField].control.setValue(data.customFields[element]);
                this.contactForm[indexField].display = true;
            }
        });
        this.checkFilling();
    }

    initBanSearch() {
632
        this.http.get('../rest/ban/availableDepartments').pipe(
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
            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();
    }

    isValidForm() {
        let state = true;

        this.contactForm.filter(contact => contact.display).forEach(element => {
650
            if (element.control.status !== 'DISABLED' && element.control.status !== 'VALID') {
651
652
                state = false;
            }
653
            element.control.markAsTouched();
654
655
656
657
658
659
660
        });

        return state;
    }

    onSubmit() {
        this.checkFilling();
661
        if (this.addressBANMode && this.emptyAddress() && !this.noAddressRequired()) {
662
            this.notify.error(this.translate.instant('lang.chooseBAN'));
663
664
665
666
667
668
669
        } else if (this.isValidForm()) {
            if (this.contactId !== null) {
                this.updateContact();
            } else {
                this.createContact();
            }
        } else {
670
            this.notify.error(this.translate.instant('lang.mustFixErrors'));
671
672
673
674
675
        }

    }

    createContact() {
676
        this.http.post('../rest/contacts', this.formatContact()).pipe(
677
            tap((data: any) => {
678
                this.onSubmitEvent.emit(data.id);
679
680
681
                if (this.appInputCorrespondentGroup !== undefined) {
                    this.appInputCorrespondentGroup.linkGrpAfterCreation(data.id, 'contact');
                }
682
                this.notify.success(this.translate.instant('lang.contactAdded'));
683
684
685
                if (!this.functions.empty(data.warning)) {
                    this.notify.error(data.warning);
                }
686
            }),
687
            // finalize(() => this.loading = false),
688
689
690
691
692
693
694
695
            catchError((err: any) => {
                this.notify.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    updateContact() {
696
        this.http.put(`../rest/contacts/${this.contactId}`, this.formatContact()).pipe(
697
            tap((data: any) => {
698
                this.onSubmitEvent.emit(this.contactId);
699
                this.notify.success(this.translate.instant('lang.contactUpdated'));
700
701
702
                if (!this.functions.empty(data) && !this.functions.empty(data.warning)) {
                    this.notify.error(data.warning);
                }
703
            }),
704
            // finalize(() => this.loading = false),
705
706
707
708
709
710
711
712
            catchError((err: any) => {
                this.notify.handleErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    formatContact() {
713
        const contact: any = {};
714
        contact['customFields'] = {};
715
        contact['externalId'] = {};
716
        const regex = /customField_[.]*/g;
717
        const regex2 = /externalId_[.]*/g;
718
719

        this.contactForm.filter(field => field.display).forEach(element => {
Alex ORLUC's avatar
Alex ORLUC committed
720
            if (element.type === 'date' && !this.functions.empty(element.control.value)) {
721
                const date = new Date(element.control.value);
Alex ORLUC's avatar
Alex ORLUC committed
722
                element.control.value = this.functions.formatDateObjectToDateString(date);
723
            }
724
            if (element.id.match(regex) !== null) {
725
                contact['customFields'][element.id.split(/_(.+)/)[1]] = element.control.value;
726
            } else if (element.id.match(regex2) !== null) {
727
                contact['externalId'][element.id.split(/_(.+)/)[1]] = element.control.value;
728
729
730
731
            } else {
                contact[element.id] = element.control.value;
            }
        });
732
        return contact;
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
    }

    isEmptyUnit(id: string) {
        if (this.contactForm.filter(field => field.display && field.unit === id).length === 0) {
            return true;
        } else {
            return false;
        }
    }

    initForm() {
        this.contactForm.forEach(element => {
            element.control = new FormControl({ value: '', disabled: false });
        });
    }

    toogleAllFieldsUnit(idUnit: string) {
        this.contactForm.filter(field => field.unit === idUnit).forEach((element: any) => {
            element.display = true;
        });
    }

    noField(id: string) {
        if (this.contactForm.filter(field => !field.display && field.unit === id).length === 0) {
            return true;
        } else {
            return false;
        }
    }

    isEmptyValue(value: string) {

765
        if (value === null || value === undefined) {
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
            return true;

        } else if (Array.isArray(value)) {
            if (value.length > 0) {
                return false;
            } else {
                return true;
            }
        } else if (String(value) !== '') {
            return false;
        } else {
            return true;
        }
    }

    checkCompany(field: any) {
782

783
        if (field.id === 'company' && field.control.value !== '' && (this.companyFound === null || this.companyFound.company !== field.control.value)) {
784
            this.http.get(`../rest/autocomplete/contacts/company?search=${field.control.value}`).pipe(
785
786
787
                tap(() => this.companyFound = null),
                filter((data: any) => data.length > 0),
                tap((data) => {
Alex ORLUC's avatar
Alex ORLUC committed
788
789
790
                    if (!this.functions.empty(data[0].addressNumber) || !this.functions.empty(data[0].addressStreet) || !this.functions.empty(data[0].addressPostcode) || !this.functions.empty(data[0].addressTown) || !this.functions.empty(data[0].addressCountry)) {
                        this.companyFound = data[0];
                    }
791

792
                }),
793
                // finalize(() => this.loading = false),
794
795
796
797
798
                catchError((err: any) => {
                    this.notify.handleErrors(err);
                    return of(false);
                })
            ).subscribe();
799
800
        } else if (field.id === 'company' && field.control.value === '') {
            this.companyFound = null;
801
802
803
804
        }
    }

    setAddress(contact: any, disableBan: boolean = true) {
805
        this.companyFound = null;
806
807
808
809
810
811
812
813
814
815
816
817
818
819
        let indexField = -1;
        Object.keys(contact).forEach(element => {
            indexField = this.contactForm.map(field => field.id).indexOf(element);
            if (!this.isEmptyValue(contact[element]) && indexField > -1 && ['company', 'addressNumber', 'addressStreet', 'addressAdditional2', 'addressPostcode', 'addressTown', 'addressCountry'].indexOf(element) > -1) {
                this.contactForm[indexField].control.setValue(contact[element]);
                this.contactForm[indexField].display = true;
            }
        });
        this.checkFilling();

        this.addressBANMode = disableBan ? false : true;
    }

    canDelete(field: any) {
820
        if (field.id === 'company') {
821
822
            const lastname = this.contactForm.filter(contact => contact.id === 'lastname')[0];
            if (lastname.display && !this.isEmptyValue(lastname.control.value)) {
823
                const valArr: ValidatorFn[] = [];
824
825
826
827
                field.control.setValidators(valArr);
                field.required = false;
                return true;
            } else {
828
                const valArr: ValidatorFn[] = [];
829
830
831
832
833
                valArr.push(Validators.required);
                field.control.setValidators(valArr);
                field.required = true;
                return false;
            }
834
        } else if (field.id === 'lastname') {
835
836
            const company = this.contactForm.filter(contact => contact.id === 'company')[0];
            if (company.display && !this.isEmptyValue(company.control.value)) {
837
                const valArr: ValidatorFn[] = [];
838
839
840
841
                field.control.setValidators(valArr);
                field.required = false;
                return true;
            } else {
842
                const valArr: ValidatorFn[] = [];
843
844
845
846
847
                valArr.push(Validators.required);
                field.control.setValidators(valArr);
                field.required = true;
                return false;
            }
848
        } else if (field.required || field.control.disabled) {
849
850
851
852
853
854
855
856
857
            return false;
        } else {
            return true;
        }
    }

    removeField(field: any) {
        field.display = !field.display;
        field.control.reset();
858
859
        if ((field.id === 'externalId_m2m' || field.id === 'communicationMeans') && !field.display) {
            const indexFieldAnnuaryId = this.contactForm.map(item => item.id).indexOf('externalId_m2m_annuary_id');
860
            if (indexFieldAnnuaryId > -1) {
861
                this.contactForm.splice(indexFieldAnnuaryId, 1);
862
863
            }
        }
864
865
866
        this.checkFilling();
    }

867
868
869
870
871
872
873
    handleCorrespondentsGroupsField(correspondentsGroups: any, field: any) {
        if (!this.functions.empty(this.contactId) && correspondentsGroups.length === 0 && this.initCorrespondentsGroups) {
            this.removeField(field);
        }
        this.initCorrespondentsGroups = false;
    }

874
    initAutocompleteCommunicationMeans() {
875
        this.communicationMeanInfo = this.translate.instant('lang.autocompleteInfo');
876
        this.communicationMeanResult = [];
877
        const indexFieldCommunicationMeans = this.contactForm.map(field => field.id).indexOf('communicationMeans');
878
        this.contactForm[indexFieldCommunicationMeans].control.valueChanges
879
880
            .pipe(
                debounceTime(300),
881
                filter((value: string) => value.length > 2),
882
883
                distinctUntilChanged(),
                tap(() => this.communicationMeanLoading = true),
884
                switchMap((data: any) => this.http.get('../rest/autocomplete/ouM2MAnnuary', { params: { 'company': data } })),
885
886
                tap((data: any) => {
                    if (this.isEmptyValue(data)) {
887
                        this.communicationMeanInfo = this.translate.instant('lang.noAvailableValue');
888
889
890
891
892
893
                    } else {
                        this.communicationMeanInfo = '';
                    }
                    this.communicationMeanResult = data;
                    this.communicationMeanFilteredResult = of(this.communicationMeanResult);
                    this.communicationMeanLoading = false;
894
895
896
897
898
                }),
                catchError((err: any) => {
                    this.communicationMeanInfo = err.error.errors;
                    this.communicationMeanLoading = false;
                    return of(false);
899
900
901
902
903
                })
            ).subscribe();
    }

    selectCommunicationMean(ev: any) {
904
        const indexFieldCommunicationMeans = this.contactForm.map(field => field.id).indexOf('communicationMeans');
905
        this.contactForm[indexFieldCommunicationMeans].control.setValue(ev.option.value.communicationValue);
906
907

        const indexFieldExternalId = this.contactForm.map(field => field.id).indexOf('externalId_m2m');
908
909
        this.contactForm[indexFieldExternalId].control.setValue(ev.option.value.businessIdValue + '/');
        this.contactForm[indexFieldExternalId].display = true;
910

911
        const indexFieldDepartment = this.contactForm.map(field => field.id).indexOf('department');
912
        this.contactForm[indexFieldDepartment].display = true;
913
914
915
    }

    initAutocompleteExternalIdM2M() {
916
        this.externalId_m2mInfo = this.translate.instant('lang.autocompleteInfo');
917
        this.externalId_m2mResult = [];
918
919
        const indexFieldCommunicationMeans = this.contactForm.map(field => field.id).indexOf('communicationMeans');
        const indexFieldExternalId = this.contactForm.map(field => field.id).indexOf('externalId_m2m');
920
        this.contactForm[indexFieldExternalId].control.valueChanges
921
922
923
            .pipe(
                debounceTime(300),
                distinctUntilChanged(),
924
                tap(() => this.externalId_m2mLoading = true),
925
                switchMap((data: any) => this.http.get('../rest/autocomplete/businessIdM2MAnnuary', { params: { 'query': data, 'communicationValue': this.contactForm[indexFieldCommunicationMeans].control.value } })),
926
927
                tap((data: any) => {
                    if (this.isEmptyValue(data)) {
928
                        this.externalId_m2mInfo = this.translate.instant('lang.noAvailableValue');
929
                    } else {
930
                        this.externalId_m2mInfo = '';
931
                    }
932
933
934
                    this.externalId_m2mResult = data;
                    this.externalId_m2mFilteredResult = of(this.externalId_m2mResult);
                    this.externalId_m2mLoading = false;
935
936
937
938
939
                }),
                catchError((err: any) => {
                    this.externalId_m2mInfo = err.error.errors;
                    this.externalId_m2mLoading = false;
                    return of(false);
940
941
942
943
944
                })
            ).subscribe();
    }

    selectExternalIdM2M(ev: any) {
945
        const indexFieldExternalId = this.contactForm.map(field => field.id).indexOf('externalId_m2m');
946
947
        this.contactForm[indexFieldExternalId].control.setValue(ev.option.value.businessIdValue);

948
        const indexFieldAnnuaryId = this.contactForm.map(field => field.id).indexOf('externalId_m2m_annuary_id');
949
950
951
952
        this.contactForm[indexFieldAnnuaryId].control.setValue(ev.option.value.entryuuid);
    }

    resetAutocompleteExternalIdM2M() {
953
954
955
956
957
958
        let indexFieldAnnuaryId = -1;
        indexFieldAnnuaryId = this.contactForm.map(field => field.id).indexOf('externalId_m2m_annuary_id');
        if (indexFieldAnnuaryId > -1) {
            this.contactForm[indexFieldAnnuaryId].control.setValue('');
        } else {
            this.contactForm.push({
959
                id: 'externalId_m2m_annuary_id',
960
                unit: 'maarch2maarch',
961
962
                label: 'm2m_annuary_id',
                type: 'string',
963
                control: new FormControl({ value: '', disabled: true }),
964
965
966
967
968
969
                required: false,
                display: true,
                filling: false,
                values: []
            });
        }
970
971
    }

972
973
974
975
976
977
978
    resetM2MFields() {
        let indexFieldAnnuaryId = -1;
        indexFieldAnnuaryId = this.contactForm.map(field => field.id).indexOf('externalId_m2m');
        this.contactForm[indexFieldAnnuaryId].control.setValue('');
        this.resetAutocompleteExternalIdM2M();
    }

979
    initAutocompleteAddressBan() {
980
        this.addressBANInfo = this.translate.instant('lang.autocompleteInfo');
981
982
983
984
985
986
987
        this.addressBANResult = [];
        this.addressBANControl.valueChanges
            .pipe(
                debounceTime(300),
                filter(value => value.length > 2),
                distinctUntilChanged(),
                tap(() => this.addressBANLoading = true),
988
                switchMap((data: any) => this.http.get('../rest/autocomplete/banAddresses', { params: { 'address': data, 'department': this.addressBANCurrentDepartment } })),
989
990
                tap((data: any) => {
                    if (data.length === 0) {
991
                        this.addressBANInfo = this.translate.instant('lang.noAvailableValue');
992
993
994
995
996
997
998
999
1000
                    } else {
                        this.addressBANInfo = '';
                    }
                    this.addressBANResult = data;
                    this.addressBANFilteredResult = of(this.addressBANResult);
                    this.addressBANLoading = false;
                })
            ).subscribe();
    }