create-external-user.component.ts 9.48 KB
Newer Older
1
import { Component, Inject, OnInit } from '@angular/core';
2
3
4
5
6
import { HttpClient } from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService } from '@service/notification/notification.service';
import { FunctionsService } from '@service/functions.service';
import { tap, catchError } from 'rxjs/operators';
7
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
8
import { of } from 'rxjs';
9
import { ContactService } from '@service/contact.service';
10
11

@Component({
12
13
    templateUrl: 'create-external-user.component.html',
    styleUrls: ['create-external-user.component.scss'],
14
    providers: [ContactService]
15
16
})

17
export class CreateExternalUserComponent implements OnInit {
18

19
    sources: any[] = [];
20

21
    currentSource: any[] = [];
22

23
    availableRoles: any[] = [
24
        {
25
            id: 'visa',
26
            label: this.translate.instant('lang.visaUser')
27
28
        },
        {
29
            id: 'sign',
30
            label: this.translate.instant('lang.signUser')
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
        }
    ];

    securityModes: any[] = [
        {
            id: 'sms',
            label: this.translate.instant('lang.sms')
        },
        {
            id: 'email',
            label: this.translate.instant('lang.email')
        }
    ];

    userOTP: any = {
        firstname: '',
        lastname: '',
        email: '',
        phone: '',
50
        security: '',
51
        sourceId: '',
52
53
54
        type: '',
        role: 'sign',
        availableRoles: this.availableRoles.map((role: any) => role.id)
55
56
    };

57
58
    correspondentShorcuts: any[] = [];

59
60
    loading: boolean = true;

61
62
    searchMode: boolean = false;

63
64
65
66
    constructor(
        public translate: TranslateService,
        public http: HttpClient,
        public functions: FunctionsService,
67
        private dialogRef: MatDialogRef<CreateExternalUserComponent>,
68
        public notify: NotificationService,
69
        private contactService: ContactService,
70
        @Inject(MAT_DIALOG_DATA) public data: any
71
72
73

    ) { }

74
    async ngOnInit(): Promise<void> {
75
        await this.getConfig();
76
77
78
79
80
        if (this.data.resId !== null) {
            this.getCorrespondents();
        } else {
            this.searchMode = true;
        }
81
82
83
84
85
86
    }

    getConfig() {
        return new Promise((resolve) => {
            this.http.get('../rest/maarchParapheurOtp').pipe(
                tap((data: any) => {
87
88
                    if (data) {
                        this.sources = data.otp;
89
90
                        this.setCurrentSource(this.data.otpInfo !== null ? this.data.otpInfo.sourceId : this.sources[0].id);
                        if (this.data.otpInfo === null) {
91
92
93
                            this.userOTP.sourceId = this.sources[0].id;
                            this.userOTP.type = this.sources[0].type;
                        } else {
94
                            this.userOTP = this.data.otpInfo;
95
                        }
96
                    }
97
                    this.loading = false;
98
99
100
101
102
103
104
105
106
                    resolve(true);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        });
    }
107
108
109
110
111
112
113
114
115
116

    addOtpUser() {
        this.dialogRef.close({otp: this.userOTP});
    }

    isValidForm() {
        return Object.values(this.userOTP).every(item => (item !== '')) && this.validFormat();
    }

    validFormat() {
117
        const phoneRegex = /^((\+)33)[1-9](\d{2}){4}$/;
118
        const emailReegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
119
        return (!this.functions.empty(this.userOTP.phone) && this.userOTP.phone.trim().match(phoneRegex) !== null) && (!this.functions.empty(this.userOTP.email) && this.userOTP.email.trim().match(emailReegex) !== null);
120
    }
121
122
123
124

    setCurrentSource(id: any) {
        const selectedSource: any = this.sources.filter((item: any) => item.id === id)[0];
        this.userOTP.type = selectedSource.type;
125
        this.currentSource = [... new Set(selectedSource.securityModes)];
126
        this.userOTP.security = this.currentSource[0];
127
    }
128
129
130
131
132

    getContact(item: any) {
        if (item.type === 'user') {
            this.http.get('../rest/users/' + item.id).pipe(
                tap((data: any) => {
133
                    const phone: string = data.phone;
134
135
136
                    this.userOTP.firstname = data.firstname;
                    this.userOTP.lastname = data.lastname;
                    this.userOTP.email = data.mail;
137
                    this.userOTP.phone = phone !== undefined ? phone.replace(/( |\.|\-)/g, '').replace('0', '+33') : '';
138
139
140
141
142
143
144
145
146
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        } else if (item.type === 'contact') {
            this.http.get('../rest/contacts/' + item.id).pipe(
                tap((data: any) => {
147
                    const phone: string = data.phone;
148
149
150
                    this.userOTP.firstname = data.firstname;
                    this.userOTP.lastname = data.lastname;
                    this.userOTP.email = data.email;
151
                    this.userOTP.phone = !this.functions.empty(phone) ? phone.replace(/( |\.|\-)/g, '').replace('0', '+33') : '';
152
153
154
155
156
157
158
159
160
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        }
    }

161
162
    formatPhone() {
        if (this.userOTP.phone.length > 1 && this.userOTP.phone[0] === '0') {
163
164
165
166
167
168
169
170
171
172
173
            this.userOTP.phone = this.userOTP.phone.replace('0', '+33');
        }
    }

    getCorrespondents() {
        this.http.get(`../rest/resources/${this.data.resId}?light=true`).pipe(
            tap((data: any) => {
                if (data.categoryId === 'outgoing') {
                    data.recipients.forEach((element: any) => {
                        this.setCorrespondentsShorcuts(element, 'recipient');
                    });
174
                } else if (data.senders !== undefined) {
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
                    data.senders.forEach((element: any) => {
                        this.setCorrespondentsShorcuts(element, 'sender');
                    });
                }
            }),
            catchError((err) => {
                this.notify.handleSoftErrors(err);
                return of(false);
            })
        ).subscribe();
    }

    setCorrespondentsShorcuts(item: any, itemCategory: string) {
        let objCorr = {};
        if (item.type === 'user') {
            this.http.get('../rest/users/' + item.id).pipe(
                tap((data: any) => {
                    objCorr = {
                        title : this.translate.instant('lang.' + itemCategory),
                        label: this.contactService.formatContact(data),
                        firstname: data.firstname,
                        lastname: data.lastname,
                        email: data.mail,
                        phone: !this.functions.empty(data.phone) ? data.phone.replace(/( |\.|\-)/g, '').replace('0', '+33') : ''
                    };
                    this.correspondentShorcuts.push(objCorr);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        } else if (item.type === 'contact') {
            this.http.get('../rest/contacts/' + item.id).pipe(
                tap((data: any) => {
                    objCorr = {
                        title : this.translate.instant('lang.' + itemCategory),
                        label: this.contactService.formatContact(data),
                        firstname: data.firstname,
                        lastname: data.lastname,
                        email: data.email,
                        phone: !this.functions.empty(data.phone) ? data.phone.replace(/( |\.|\-)/g, '').replace('0', '+33') : ''
                    };
                    this.correspondentShorcuts.push(objCorr);
                }),
                catchError((err: any) => {
                    this.notify.handleSoftErrors(err);
                    return of(false);
                })
            ).subscribe();
        }
    }

    setOtpInfoFromShortcut(item: any) {
        this.userOTP.firstname = item.firstname;
        this.userOTP.lastname = item.lastname;
        this.userOTP.email = item.email;
        this.userOTP.phone = item.phone;
233
        this.formatPhone();
234
235
    }

236
237
238
    getRegexPhone() {
        // map country calling code with national number length
        const phonesMap = {
239
240
241
242
243
244
245
246
247
            '32': [8, 10],      // Belgium
            '41': [4, 12],      // Swiss
            '44': [7, 10],      // United Kingdom
            '352': [4, 11],     // Luxembourg
            '351': [9, 11],     // Portugal
            '33': 9,            // France
            '1' : 10,           // USA
            '39': 11,           // Italy
            '34': 9             // Spain
248
249
250
251
252
253
254
255
256
257
258
259
260
        };
        const regex = Object.keys(phonesMap).reduce((phoneFormats: any [], countryCode: any) => {
            const numberLength = phonesMap[countryCode];
            if (Array.isArray(numberLength)) {
                phoneFormats.push('(\\+' + countryCode + `[0-9]\{${numberLength[0]},${numberLength[1]}\})`);
            } else {
                phoneFormats.push('(\\+' + countryCode + `[0-9]\{${numberLength}\})`);
            }
            return phoneFormats;
        }, []).join('|');
        return new RegExp(`^(${regex})$`);
    };

261
}