user-administration.component.ts 45.4 KB
Newer Older
1
import { Component, OnInit, NgZone, ViewChild, Inject, TemplateRef, ViewContainerRef } from '@angular/core';
Damien's avatar
Damien committed
2
import { HttpClient } from '@angular/common/http';
3
import { ActivatedRoute, Router } from '@angular/router';
4
import { TranslateService } from '@ngx-translate/core';
5
6
7
8
9
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';
10
import { FormGroup, Validators, AbstractControl, ValidationErrors, ValidatorFn, FormBuilder } from '@angular/forms';
11
12
import { NotificationService } from '@service/notification/notification.service';
import { HeaderService } from '@service/header.service';
13
import { SelectionModel } from '@angular/cdk/collections';
14
import { AccountLinkComponent } from './account-link/account-link.component';
15
16
import { AppService } from '@service/app.service';
import { PrivilegeService } from '@service/privileges.service';
17
import { MaarchFlatTreeComponent } from '../../../plugins/tree/maarch-flat-tree.component';
18
import { environment } from '../../../environments/environment';
19
import { InputCorrespondentGroupComponent } from '../contact/group/inputCorrespondent/input-correspondent-group.component';
20
import { AuthService } from '@service/auth.service';
21
22
23
import { ConfirmComponent } from '@plugins/modal/confirm.component';
import { catchError, exhaustMap, filter, tap } from 'rxjs/operators';
import { of } from 'rxjs';
Damien's avatar
Damien committed
24

25
declare let $: any;
Damien's avatar
Damien committed
26
27

@Component({
28
    templateUrl: 'user-administration.component.html',
29
    styleUrls: ['user-administration.component.scss']
Damien's avatar
Damien committed
30
})
31
export class UserAdministrationComponent implements OnInit {
32

33
    @ViewChild('snav2', { static: true }) public sidenavRight: MatSidenav;
34
    @ViewChild('adminMenuTemplate', { static: true }) adminMenuTemplate: TemplateRef<any>;
35
    @ViewChild('maarchTree', { static: false }) maarchTree: MaarchFlatTreeComponent;
36
    @ViewChild('appInputCorrespondentGroup', { static: false }) appInputCorrespondentGroup: InputCorrespondentGroupComponent;
37
38
    @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
    @ViewChild(MatSort, { static: false }) sort: MatSort;
39

40
41
    loading: boolean = false;
    dialogRef: MatDialogRef<any>;
Alex ORLUC's avatar
Alex ORLUC committed
42
    highlightMe: boolean = false;
43
44
45
46
    config: any = {};
    serialId: number;
    userId: string;
    mode: string = '';
47
    user: any = {
48
49
        mode: 'standard',
        authorizedApi: ''
50
    };
51
52
53
54
    _search: string = '';
    creationMode: boolean;

    signatureModel: any = {
55
56
57
58
        base64: '',
        base64ForJs: '',
        name: '',
        type: '',
Alex ORLUC's avatar
Alex ORLUC committed
59
        size: 0,
60
        label: '',
61
    };
62
63
64
65
66
    userAbsenceModel: any[] = [];
    userList: any[] = [];
    maarchParapheurLink: any = {
        login: '',
        picture: ''
67
    };
68
    selectedSignature: number = -1;
69
    selectedSignatureLabel: string = '';
70
71
72
73
74
75
76
77
78
79
80
81
    loadingSign: boolean = false;
    data: any[] = [];
    CurrentYear: number = new Date().getFullYear();
    currentMonth: number = new Date().getMonth() + 1;
    minDate: Date = new Date();
    firstFormGroup: FormGroup;
    ruleText: string = '';
    otherRuleText: string;
    validPassword: boolean = false;
    showPassword: boolean = false;
    hidePassword: boolean = true;
    passwordModel: any = {
82
83
84
        currentPassword: '',
        newPassword: '',
        reNewPassword: ''
Damien's avatar
Damien committed
85
    };
86
87
88
89
90
91
92
    passwordRules: any = {
        minLength: { enabled: false, value: 0 },
        complexityUpper: { enabled: false, value: 0 },
        complexityNumber: { enabled: false, value: 0 },
        complexitySpecial: { enabled: false, value: 0 },
        renewal: { enabled: false, value: 0 },
        historyLastUse: { enabled: false, value: 0 }
Damien's avatar
Damien committed
93
    };
94

95
    displayedColumns = ['event_date', 'record_id', 'info', 'remote_ip'];
96
97
    dataSource = new MatTableDataSource(this.data);
    selectedTabIndex: number = 0;
98
    maarchParapheurConnectionStatus = true;
99

100
101
102
    canViewPersonalDatas: boolean = false;
    canManagePersonalDatas: boolean = false;

103
104
105
    adminModes: any[] = [
        {
            id: 'standard',
106
            label: this.translate.instant('lang.standard')
107
108
109
        },
        {
            id: 'root_visible',
110
            label: this.translate.instant('lang.root_visible')
111
112
113
        },
        {
            id: 'root_invisible',
114
            label: this.translate.instant('lang.root_invisible')
115
116
117
        },
        {
            id: 'rest',
118
            label: this.translate.instant('lang.rest')
119
        }
120
121
    ];

122
123
    appVersion: string = environment.VERSION.split('.')[0] + '.' + environment.VERSION.split('.')[1];

124
125
126
    // Redirect Baskets
    selectionBaskets = new SelectionModel<Element>(true, []);

127
    constructor(
128
        public translate: TranslateService,
129
130
131
132
133
134
        public http: HttpClient,
        private route: ActivatedRoute,
        private router: Router,
        private zone: NgZone,
        private notify: NotificationService,
        public dialog: MatDialog,
Florian Azizian's avatar
Florian Azizian committed
135
        public headerService: HeaderService,
136
        private _formBuilder: FormBuilder,
137
        public appService: AppService,
138
        public authService: AuthService,
139
140
        private privilegeService: PrivilegeService,
        private viewContainerRef: ViewContainerRef
141
    ) {
142
143
144
        window['angularUserAdministrationComponent'] = {
            componentAfterUpload: (base64Content: any) => this.processAfterUpload(base64Content),
        };
Damien's avatar
Damien committed
145
146
    }

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
    applyFilter(filterValue: string) {
        filterValue = filterValue.trim();
        filterValue = filterValue.toLowerCase();
        this.dataSource.filter = filterValue;
    }

    masterToggleBaskets(event: any) {
        if (event.checked) {
            this.user.baskets.forEach((basket: any) => {
                if (!basket.userToDisplay) {
                    this.selectionBaskets.select(basket);
                }
            });
        } else {
            this.selectionBaskets.clear();
        }
    }

Damien's avatar
Damien committed
165
166
167
    ngOnInit(): void {
        this.loading = true;

168
        this.headerService.injectInSideBarLeft(this.adminMenuTemplate, this.viewContainerRef, 'adminMenu');
169

170
        this.route.params.subscribe((params: any) => {
171

172
            if (typeof params['id'] === 'undefined') {
173

174
                this.headerService.setHeader(this.translate.instant('lang.userCreation'));
Alex ORLUC's avatar
Alex ORLUC committed
175
                this.creationMode = true;
176
177
                this.canViewPersonalDatas = false;
                this.canManagePersonalDatas = this.privilegeService.hasCurrentUserPrivilege('manage_personal_data');
Damien's avatar
Damien committed
178
                this.loading = false;
179
            } else {
180

Alex ORLUC's avatar
Alex ORLUC committed
181
                this.creationMode = false;
182
                this.serialId = params['id'];
183
                this.http.get('../rest/users/' + this.serialId + '/details')
Alex ORLUC's avatar
Alex ORLUC committed
184
                    .subscribe((data: any) => {
185
                        this.user = data;
186

187
                        if (this.user.mode === 'rest') {
188
189
190
                            this.user.authorizedApi = this.user.authorizedApi.join('\n');
                        }

191
192
193
194
195
196
197
                        if (this.headerService.user.id === this.user.id) {
                            this.canViewPersonalDatas = true;
                            this.canManagePersonalDatas = true;
                        } else {
                            this.canViewPersonalDatas = this.privilegeService.hasCurrentUserPrivilege('view_personal_data');
                            this.canManagePersonalDatas = this.privilegeService.hasCurrentUserPrivilege('manage_personal_data');
                        }
198

199
200
201
                        if (this.canManagePersonalDatas) {
                            this.canViewPersonalDatas = true;
                        }
202
203
204
                        if (!this.canViewPersonalDatas) {
                            this.user.phone = '****';
                        }
Alex ORLUC's avatar
Alex ORLUC committed
205
                        this.data = data.history;
206
                        this.userId = data.user_id;
Alex ORLUC's avatar
Alex ORLUC committed
207
                        this.minDate = new Date(this.CurrentYear + '-' + this.currentMonth + '-01');
208
                        this.headerService.setHeader(this.translate.instant('lang.userModification'), data.firstname + ' ' + data.lastname);
209
210
211
212
213

                        if (this.user.external_id.maarchParapheur !== undefined) {
                            this.checkInfoMaarchParapheurAccount();
                        }

214
                        this.loading = false;
Alex ORLUC's avatar
Alex ORLUC committed
215
216
217
218
219
                        setTimeout(() => {
                            this.dataSource = new MatTableDataSource(this.data);
                            this.dataSource.paginator = this.paginator;
                            this.dataSource.sort = this.sort;
                        }, 0);
220
221
                    }, (err) => {
                        this.notify.handleErrors(err);
222
223
                    });
            }
Damien's avatar
Damien committed
224
225
226
        });
    }

227
    checkInfoMaarchParapheurAccount() {
228
        this.http.get('../rest/users/' + this.serialId + '/statusInMaarchParapheur')
229
230
231
232
233
            .subscribe((data: any) => {
                this.maarchParapheurLink.login = data.link;
                this.loading = false;
                if (this.maarchParapheurLink.login !== '') {
                    this.loadAvatarMaarchParapheur(this.user.external_id.maarchParapheur);
234
235
                } else {
                    this.maarchParapheurConnectionStatus = false;
236
237
238
239
240
                }
            });
    }

    linkMaarchParapheurAccount() {
241
        const dialogRef = this.dialog.open(AccountLinkComponent, { panelClass: 'maarch-modal', autoFocus: false, data: { user: this.user } });
242
243
244
245
246
247
248
249
250
251
252
253
254
        dialogRef.afterClosed().subscribe(result => {
            if (result) {
                if (result.inMaarchParapheur) {
                    this.linkAccountToMaarchParahpeur(result.id);
                } else {
                    this.createAccountToMaarchParahpeur(result.id, result.login);
                }

            }
        });
    }

    linkAccountToMaarchParahpeur(externalId: number) {
255
        this.http.put('../rest/users/' + this.serialId + '/linkToMaarchParapheur', { maarchParapheurUserId: externalId })
256
257
258
259
            .subscribe(() => {
                this.user.canCreateMaarchParapheurUser = false;
                this.user.external_id['maarchParapheur'] = externalId;
                this.checkInfoMaarchParapheurAccount();
260
                this.notify.success(this.translate.instant('lang.accountLinked'));
261
262
263
264
265
266
            }, (err) => {
                this.notify.error(err.error.errors);
            });
    }

    createAccountToMaarchParahpeur(id: number, login: string) {
267
        this.http.put('../rest/users/' + id + '/createInMaarchParapheur', { login: login })
268
269
270
271
            .subscribe((data: any) => {
                this.user.canCreateMaarchParapheurUser = false;
                this.user.external_id['maarchParapheur'] = data.externalId;
                this.checkInfoMaarchParapheurAccount();
272
                this.notify.success(this.translate.instant('lang.accountAdded'));
273
            }, (err) => {
274
                if (err.error.errors === 'Login already exists') {
275
                    err.error.errors = this.translate.instant('lang.loginAlreadyExistsInMaarchParapheur');
276
                }
277
278
279
280
281
                this.notify.error(err.error.errors);
            });
    }

    loadAvatarMaarchParapheur(externalId: number) {
282
        this.http.get('../rest/maarchParapheur/user/' + externalId + '/picture')
283
284
285
286
287
288
289
290
291
            .subscribe((data: any) => {
                this.maarchParapheurLink.picture = data.picture;

            }, (err) => {
                this.notify.handleErrors(err);
            });
    }

    unlinkMaarchParapheurAccount() {
292
293
294
295
296
297
298
299
300
301
302
303
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.unlinkAccount')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.put('../rest/users/' + this.serialId + '/unlinkToMaarchParapheur', {})),
            tap(() => {
                this.user.canCreateMaarchParapheurUser = true;
                this.maarchParapheurLink.login = '';
                this.maarchParapheurLink.picture = '';
                this.notify.success(this.translate.instant('lang.accountUnlinked'));
                this.maarchParapheurConnectionStatus = true;
            }),
            catchError((err: any) => {
304
                this.notify.handleSoftErrors(err);
305
306
307
                return of(false);
            })
        ).subscribe();
308
309
    }

Alex ORLUC's avatar
Alex ORLUC committed
310
    toogleRedirect(basket: any) {
311
        $('#redirectUser_' + basket.group_id + '_' + basket.basket_id).toggle();
312

313
        this.http.get('../rest/users')
Alex ORLUC's avatar
Alex ORLUC committed
314
            .subscribe((data: any) => {
315
                // this.userList = data['users'];
316

317
318
            }, (err) => {
                this.notify.handleErrors(err);
Alex ORLUC's avatar
Alex ORLUC committed
319
            });
320
321
    }

Alex ORLUC's avatar
Alex ORLUC committed
322
    initService() {
323
        if (this.maarchTree.rawData.length === 0) {
324
325
326
327
            this.maarchTree.initData(this.user.allEntities.map((ent: any) => ({
                ...ent,
                parent_id : ent.parent,
            })));
328
        }
329
        /* if ($('.jstree-container-ul').length === 0) {
330
331
332
            $('#jstree').jstree({
                'checkbox': {
                    'three_state': false // no cascade selection
333
                },
Alex ORLUC's avatar
Alex ORLUC committed
334
                'core': {
335
                    force_text: true,
336
337
338
339
                    'themes': {
                        'name': 'proton',
                        'responsive': true
                    },
Alex ORLUC's avatar
Alex ORLUC committed
340
                    'data': this.user.allEntities
341
                },
342
                'plugins': ['checkbox', 'search']
343
            });
344
            $('#jstree')
Alex ORLUC's avatar
Alex ORLUC committed
345
346
                // listen for event
                .on('select_node.jstree', (e: any, data: any) => {
347
                    if (this.mode === '') {
348
                        this.addEntity(data.node.id);
349
                    }
Alex ORLUC's avatar
Alex ORLUC committed
350
351
352
353
354
355
                }).on('deselect_node.jstree', (e: any, data: any) => {
                    this.deleteEntity(data.node.id);
                })
                // create the instance
                .jstree();

356
357
            let to: any = false;
            $('#jstree_search').keyup(function () {
Alex ORLUC's avatar
Alex ORLUC committed
358
359
                if (to) { clearTimeout(to); }
                to = setTimeout(function () {
360
361
                    const v: any = $('#jstree_search').val();
                    $('#jstree').jstree(true).search(v);
Alex ORLUC's avatar
Alex ORLUC committed
362
                }, 250);
363
            });
364
        }*/
365
366
    }

367
368
369
370
371
372
    processAfterUpload(b64Content: any) {
        this.zone.run(() => this.resfreshUpload(b64Content));
    }

    resfreshUpload(b64Content: any) {
        if (this.signatureModel.size <= 2000000) {
373
            this.signatureModel.base64 = b64Content.replace(/^data:.*?;base64,/, '');
374
375
            this.signatureModel.base64ForJs = b64Content;
        } else {
376
            this.signatureModel.name = '';
377
            this.signatureModel.size = 0;
378
379
380
            this.signatureModel.type = '';
            this.signatureModel.base64 = '';
            this.signatureModel.base64ForJs = '';
381

382
            this.notify.error('Taille maximum de fichier dépassée (2 MB)');
383
384
385
386
        }
    }

    clickOnUploader(id: string) {
387
        $('#' + id).click();
388
389
390
391
    }

    uploadSignatureTrigger(fileInput: any) {
        if (fileInput.target.files && fileInput.target.files[0]) {
392
            const reader = new FileReader();
393
394
395
396

            this.signatureModel.name = fileInput.target.files[0].name;
            this.signatureModel.size = fileInput.target.files[0].size;
            this.signatureModel.type = fileInput.target.files[0].type;
397
            if (this.signatureModel.label === '') {
398
399
400
401
402
                this.signatureModel.label = this.signatureModel.name;
            }

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

403
            reader.onload = (value: any) => {
404
                window['angularUserAdministrationComponent'].componentAfterUpload(value.target.result);
405
                this.submitSignature();
406
407
408
409
410
411
412
413
414
            };
        }
    }

    displaySignatureEditionForm(index: number) {
        this.selectedSignature = index;
        this.selectedSignatureLabel = this.user.signatures[index].signature_label;
    }

Alex ORLUC's avatar
Alex ORLUC committed
415
    resendActivationNotification() {
416
417
418
419
420
421
422
423
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.sendActivationNotification')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.put('../rest/users/' + this.serialId + '/accountActivationNotification', {})),
            tap(() => {
                this.notify.success(this.translate.instant('lang.activationNotificationSend'));
            }),
            catchError((err: any) => {
424
                this.notify.handleSoftErrors(err);
425
426
427
                return of(false);
            })
        ).subscribe();
428
429
    }

Alex ORLUC's avatar
Alex ORLUC committed
430
    toggleGroup(group: any) {
431
432
433
434
        if ($('#' + group.group_id + '-input').is(':checked') === true) {
            const groupReq = {
                'groupId': group.group_id,
                'role': group.role
435
            };
436
            this.http.post('../rest/users/' + this.serialId + '/groups', groupReq)
437
                .subscribe(async (data: any) => {
Alex ORLUC's avatar
Alex ORLUC committed
438
439
                    this.user.groups = data.groups;
                    this.user.baskets = data.baskets;
440
                    if (this.headerService.user.id == this.serialId) {
441
442
                        await this.headerService.resfreshCurrentUser();
                        this.privilegeService.resfreshUserShortcuts();
443
                    }
444
                    this.notify.success(this.translate.instant('lang.groupAdded'));
Alex ORLUC's avatar
Alex ORLUC committed
445
446
447
448
                }, (err) => {
                    this.notify.error(err.error.errors);
                });
        } else {
449
            this.http.delete('../rest/users/' + this.serialId + '/groups/' + group.group_id)
450
                .subscribe(async (data: any) => {
Alex ORLUC's avatar
Alex ORLUC committed
451
                    this.user.groups = data.groups;
452
                    this.user.baskets = data.baskets;
453
                    this.user.redirectedBaskets = data.redirectedBaskets;
454
                    if (this.headerService.user.id == this.serialId) {
455
456
                        await this.headerService.resfreshCurrentUser();
                        this.privilegeService.resfreshUserShortcuts();
457
                    }
458
                    this.notify.success(this.translate.instant('lang.groupDeleted'));
Alex ORLUC's avatar
Alex ORLUC committed
459
460
461
                }, (err) => {
                    this.notify.error(err.error.errors);
                });
462
463
        }
    }
464

465
    updateGroup(group: any) {
466
        this.http.put('../rest/users/' + this.serialId + '/groups/' + group.group_id, group)
Alex ORLUC's avatar
Alex ORLUC committed
467
            .subscribe((data: any) => {
468
                this.notify.success(this.translate.instant('lang.groupUpdated'));
469
            }, (err) => {
470
                this.notify.error(err.error.errors);
471
472
473
            });
    }

474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    addEntity(entities: any[]) {
        entities.forEach(ent => {
            const entity = {
                'entityId': ent.entity_id,
                'role': ''
            };
            this.http.post('../rest/users/' + this.serialId + '/entities', entity)
                .subscribe((data: any) => {
                    this.user.entities = data.entities;
                    this.user.allEntities = data.allEntities;
                    if (this.headerService.user.id == this.serialId) {
                        this.headerService.resfreshCurrentUser();
                    }
                    this.notify.success(this.translate.instant('lang.entityAdded'));
                }, (err) => {
                    this.notify.error(err.error.errors);
                });
        });
492
493
494

    }

495
    updateEntity(entity: any) {
496
        this.http.put('../rest/users/' + this.serialId + '/entities/' + entity.entity_id, entity)
497
            .subscribe(() => {
498
                this.notify.success(this.translate.instant('lang.entityUpdated'));
499
            }, (err) => {
500
                this.notify.error(err.error.errors);
501
502
503
504
            });
    }

    updatePrimaryEntity(entity: any) {
505
        this.http.put('../rest/users/' + this.serialId + '/entities/' + entity.entity_id + '/primaryEntity', {})
Alex ORLUC's avatar
Alex ORLUC committed
506
            .subscribe((data: any) => {
507
                this.user['entities'] = data.entities;
508
                this.notify.success(this.translate.instant('lang.entityTooglePrimary') + ' « ' + entity.entity_id + ' »');
509
            }, (err) => {
510
                this.notify.error(err.error.errors);
511
512
513
            });
    }

514
    deleteEntity(entities: any[]) {
515

516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        entities.forEach(ent => {
            const entityId = ent.entity_id;
            // first check confidential state
            this.http.get('../rest/users/' + this.serialId + '/entities/' + entityId)
                .subscribe((data: any) => {
                    if (!data['hasConfidentialityInstances'] && !data['hasListTemplates']) {
                        this.http.delete('../rest/users/' + this.serialId + '/entities/' + entityId)
                            .subscribe((dataEntities: any) => {
                                this.user.entities = dataEntities.entities;
                                this.user.allEntities = dataEntities.allEntities;
                                if (this.headerService.user.id == this.serialId) {
                                    this.headerService.resfreshCurrentUser();
                                }
                                this.notify.success(this.translate.instant('lang.entityDeleted'));
                            }, (err) => {
                                this.notify.error(err.error.errors);
                            });
                    } else {
                        this.config = { panelClass: 'maarch-modal', data: { hasConfidentialityInstances: data['hasConfidentialityInstances'], hasListTemplates: data['hasListTemplates'] } };
                        this.dialogRef = this.dialog.open(UserAdministrationRedirectModalComponent, this.config);
                        this.dialogRef.afterClosed().subscribe((result: any) => {
                            this.mode = 'delete';
                            if (result) {
                                this.mode = result.processMode;
                                this.http.request('DELETE', '../rest/users/' + this.serialId + '/entities/' + entityId, { body: { 'mode': this.mode, 'newUser': result.newUser } })
                                    .subscribe((dataEntities: any) => {
                                        this.user.entities = dataEntities.entities;
                                        this.user.allEntities = dataEntities.allEntities;
                                        if (this.headerService.user.id == this.serialId) {
                                            this.headerService.resfreshCurrentUser();
                                        }
                                        this.notify.success(this.translate.instant('lang.entityDeleted'));
                                    }, (err) => {
                                        this.notify.error(err.error.errors);
                                    });
                            } else {
                                this.maarchTree.toggleNode(
                                    this.maarchTree.dataSource.data,
                                    {
                                        selected: true,
                                        opened: true
                                    },
                                    [ent.id]
                                );
                                // $('#jstree').jstree('select_node', entityId);
                                this.mode = '';
562
                            }
563
                            this.dialogRef = null;
564
                        });
565
566
567
568
569
570
                    }

                }, (err) => {
                    this.notify.error(err.error.errors);
                });
        });
571

572
573
    }

574
    submitSignature() {
575
        this.http.post('../rest/users/' + this.serialId + '/signatures', this.signatureModel)
Alex ORLUC's avatar
Alex ORLUC committed
576
            .subscribe((data: any) => {
577
                this.user.signatures = data.signatures;
578
                this.notify.success(this.translate.instant('lang.signAdded'));
Alex ORLUC's avatar
Alex ORLUC committed
579
                this.signatureModel = {
580
581
582
583
                    base64: '',
                    base64ForJs: '',
                    name: '',
                    type: '',
Alex ORLUC's avatar
Alex ORLUC committed
584
                    size: 0,
585
                    label: '',
586
587
                };
            }, (err) => {
588
                this.notify.error(err.error.errors);
589
590
591
            });
    }

Alex ORLUC's avatar
Alex ORLUC committed
592
    updateSignature(selectedSignature: any) {
593
594
        const id = this.user.signatures[selectedSignature].id;
        const label = this.user.signatures[selectedSignature].signature_label;
Alex ORLUC's avatar
Alex ORLUC committed
595

596
        this.http.put('../rest/users/' + this.serialId + '/signatures/' + id, { 'label': label })
Alex ORLUC's avatar
Alex ORLUC committed
597
            .subscribe((data: any) => {
598
                this.user.signatures[selectedSignature].signature_label = data.signature.signature_label;
599
                this.notify.success(this.translate.instant('lang.signUpdated'));
600
            }, (err) => {
601
                this.notify.error(err.error.errors);
602
603
604
            });
    }

Alex ORLUC's avatar
Alex ORLUC committed
605
    deleteSignature(signature: any) {
606
607
608
609
610
611
612
613
614
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.delete')} « ${signature.signature_label} »`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.delete('../rest/users/' + this.serialId + '/signatures/' + signature.id)),
            tap((data: any) => {
                this.user.signatures = data.signatures;
                this.notify.success(this.translate.instant('lang.signDeleted'));
            }),
            catchError((err: any) => {
615
                this.notify.handleSoftErrors(err);
616
617
618
                return of(false);
            })
        ).subscribe();
619
620
    }

621
    test(event: any) {
622
        if (event.mouseEvent.dataTransfer.files && event.mouseEvent.dataTransfer.files[0]) {
623
            const reader = new FileReader();
624
625
626
627

            this.signatureModel.name = event.mouseEvent.dataTransfer.files[0].name;
            this.signatureModel.size = event.mouseEvent.dataTransfer.files[0].size;
            this.signatureModel.type = event.mouseEvent.dataTransfer.files[0].type;
628
            if (this.signatureModel.label === '') {
629
630
631
632
633
634
635
636
637
638
639
640
                this.signatureModel.label = this.signatureModel.name;
            }

            reader.readAsDataURL(event.mouseEvent.dataTransfer.files[0]);

            reader.onload = (value: any) => {
                window['angularUserAdministrationComponent'].componentAfterUpload(value.target.result);
                this.submitSignature();
            };
        }
    }

641
    addBasketRedirection(newUser: any) {
642
        const basketsRedirect: any[] = [];
643
644
645
646
        this.selectionBaskets.selected.forEach((elem: any) => {
            basketsRedirect.push(
                {
                    actual_user_id: newUser.serialId,
647
648
                    basket_id: elem.basket_id,
                    group_id: elem.groupSerialId,
649
650
                    originalOwner: null
                }
651
            );
652
        });
653
654
655
656
657
658
659
660
661
662
663
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.redirectBasket')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.post('../rest/users/' + this.serialId + '/redirectedBaskets', basketsRedirect)),
            tap((data: any) => {
                this.user.baskets = data['baskets'];
                this.user.redirectedBaskets = data['redirectedBaskets'];
                this.selectionBaskets.clear();
                this.notify.success(this.translate.instant('lang.basketUpdated'));
            }),
            catchError((err: any) => {
664
                this.notify.handleSoftErrors(err);
665
666
667
                return of(false);
            })
        ).subscribe();
668
669
    }

670
    reassignBasketRedirection(newUser: any, basket: any, i: number) {
671
672
673
674
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.redirectBasket')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.post('../rest/users/' + this.serialId + '/redirectedBaskets', [
675
                {
676
677
678
679
                    'actual_user_id': newUser.serialId,
                    'basket_id': basket.basket_id,
                    'group_id': basket.group_id,
                    'originalOwner': basket.owner_user_id,
680
                }
681
682
683
684
685
686
687
            ])),
            tap((data: any) => {
                this.user.baskets = data['baskets'];
                this.user.assignedBaskets.splice(i, 1);
                this.notify.success(this.translate.instant('lang.basketUpdated'));
            }),
            catchError((err: any) => {
688
                this.notify.handleSoftErrors(err);
689
690
691
                return of(false);
            })
        ).subscribe();
692
693
694
    }

    delBasketRedirection(basket: any, i: number) {
695
696
697
698
699
700
701
702
703
704
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.deleteRedirection')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.delete('../rest/users/' + this.serialId + '/redirectedBaskets?redirectedBasketIds[]=' + basket.id)),
            tap((data: any) => {
                this.user.baskets = data['baskets'];
                this.user.redirectedBaskets.splice(i, 1);
                this.notify.success(this.translate.instant('lang.basketUpdated'));
            }),
            catchError((err: any) => {
705
                this.notify.handleSoftErrors(err);
706
707
708
                return of(false);
            })
        ).subscribe();
709
710
    }

711
    delBasketAssignRedirection(basket: any, i: number) {
712
713
714
715
716
717
718
719
720
721
        const dialogRef = this.dialog.open(ConfirmComponent, { panelClass: 'maarch-modal', autoFocus: false, disableClose: true, data: { title: `${this.translate.instant('lang.deleteAssignation')}`, msg: this.translate.instant('lang.confirmAction') } });
        dialogRef.afterClosed().pipe(
            filter((data: string) => data === 'ok'),
            exhaustMap(() => this.http.delete('../rest/users/' + this.serialId + '/redirectedBaskets?redirectedBasketIds[]=' + basket.id)),
            tap((data: any) => {
                this.user.baskets = data['baskets'];
                this.user.assignedBaskets.splice(i, 1);
                this.notify.success(this.translate.instant('lang.basketUpdated'));
            }),
            catchError((err: any) => {
722
                this.notify.handleSoftErrors(err);
723
724
725
                return of(false);
            })
        ).subscribe();
726
727
    }

728
    toggleBasket(state: boolean) {
729
        const basketsDisable: any = [];
730
        this.user.baskets.forEach((elem: any) => {
731
            this.selectionBaskets.selected.forEach((selected: any) => {
732
                if (elem.basket_id === selected.basket_id && elem.group_id === selected.group_id && elem.allowed !== state) {
733
                    elem.allowed = state;
734
                    basketsDisable.push({ 'basketId': elem.basket_id, 'groupSerialId': elem.groupSerialId, 'allowed': state });
735
736
                }
            });
737
        });
738
        if (basketsDisable.length > 0) {
739
            this.http.put('../rest/users/' + this.serialId + '/baskets', { 'baskets': basketsDisable })
740
741
                .subscribe((data: any) => {
                    this.selectionBaskets.clear();
742
                    this.notify.success(this.translate.instant('lang.basketsUpdated'));
743
744
745
                }, (err: any) => {
                    this.notify.error(err.error.errors);
                });
746
        }
747
748
    }

749
    activateAbsence() {
750
        this.http.put('../rest/users/' + this.serialId + '/status', { 'status': 'ABS' })
Alex ORLUC's avatar
Alex ORLUC committed
751
            .subscribe((data: any) => {
752
                this.user.status = data.user.status;
Alex ORLUC's avatar
Alex ORLUC committed
753
                this.userAbsenceModel = [];
754
                this.notify.success(this.translate.instant('lang.absOn'));
755
            }, (err) => {
756
                this.notify.error(err.error.errors);
757
758
            });
    }
759

760
    desactivateAbsence() {
761
        this.http.put('../rest/users/' + this.serialId + '/status', { 'status': 'OK' })
Alex ORLUC's avatar
Alex ORLUC committed
762
            .subscribe((data: any) => {
Damien's avatar
Damien committed
763
                this.user.status = data.user.status;
764
                this.notify.success(this.translate.instant('lang.absOff'));
Damien's avatar
Damien committed
765
766
767
768
769
770
            }, (err: any) => {
                this.notify.error(err.error.errors);
            });
    }

    getErrorMessage() {
771
        if (this.firstFormGroup.controls['newPasswordCtrl'].value !== this.firstFormGroup.controls['retypePasswordCtrl'].value) {
772
            this.firstFormGroup.controls['retypePasswordCtrl'].setErrors({ 'mismatch': true });
Damien's avatar
Damien committed
773
774
775
776
        } else {
            this.firstFormGroup.controls['retypePasswordCtrl'].setErrors(null);
        }
        if (this.firstFormGroup.controls['newPasswordCtrl'].hasError('required')) {
777
            return this.translate.instant('lang.requiredField') + ' !';
Damien's avatar
Damien committed
778
779

        } else if (this.firstFormGroup.controls['newPasswordCtrl'].hasError('minlength') && this.passwordRules.minLength.enabled) {
780
            return this.passwordRules.minLength.value + ' ' + this.translate.instant('lang.passwordminLength') + ' !';
Damien's avatar
Damien committed
781
782

        } else if (this.firstFormGroup.controls['newPasswordCtrl'].errors != null && this.firstFormGroup.controls['newPasswordCtrl'].errors.complexityUpper !== undefined && this.passwordRules.complexityUpper.enabled) {
783
            return this.translate.instant('lang.passwordcomplexityUpper') + ' !';
Damien's avatar
Damien committed
784
785

        } else if (this.firstFormGroup.controls['newPasswordCtrl'].errors != null && this.firstFormGroup.controls['newPasswordCtrl'].errors.complexityNumber !== undefined && this.passwordRules.complexityNumber.enabled) {
786
            return this.translate.instant('lang.passwordcomplexityNumber') + ' !';
Damien's avatar
Damien committed
787
788

        } else if (this.firstFormGroup.controls['newPasswordCtrl'].errors != null && this.firstFormGroup.controls['newPasswordCtrl'].errors.complexitySpecial !== undefined && this.passwordRules.complexitySpecial.enabled) {
789
            return this.translate.instant('lang.passwordcomplexitySpecial') + ' !';
Damien's avatar
Damien committed
790
791
792
793
794
795
796
797
798

        } else {
            this.firstFormGroup.controls['newPasswordCtrl'].setErrors(null);
            this.validPassword = true;
            return '';
        }
    }

    matchValidator(group: FormGroup) {
799
        if (group.controls['newPasswordCtrl'].value === group.controls['retypePasswordCtrl'].value) {
Damien's avatar
Damien committed
800
801
            return false;
        } else {
802
803
            group.controls['retypePasswordCtrl'].setErrors({ 'mismatch': true });
            return { 'mismatch': true };
Damien's avatar
Damien committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
        }
    }

    regexValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            if (!control.value) {
                return null;
            }
            const valid = regex.test(control.value);
            return valid ? null : error;
        };
    }

    changePasswd() {
818
        this.http.get('../rest/passwordRules')
Damien's avatar
Damien committed
819
            .subscribe((data: any) => {
820
821
822
                const valArr: ValidatorFn[] = [];
                const ruleTextArr: String[] = [];
                const otherRuleTextArr: String[] = [];
Damien's avatar
Damien committed
823
824
825
826

                valArr.push(Validators.required);

                data.rules.forEach((rule: any) => {
827
                    if (rule.label === 'minLength') {
Damien's avatar
Damien committed
828
829
830
831
                        this.passwordRules.minLength.enabled = rule.enabled;
                        this.passwordRules.minLength.value = rule.value;
                        if (rule.enabled) {
                            valArr.push(Validators.minLength(this.passwordRules.minLength.value));
832
                            ruleTextArr.push(rule.value + ' ' + this.translate.instant('lang.password' + rule.label));
Damien's avatar
Damien committed
833
834
835
                        }


836
                    } else if (rule.label === 'complexityUpper') {
Damien's avatar
Damien committed
837
838
839
840
                        this.passwordRules.complexityUpper.enabled = rule.enabled;
                        this.passwordRules.complexityUpper.value = rule.value;
                        if (rule.enabled) {
                            valArr.push(this.regexValidator(new RegExp('[A-Z]'), { 'complexityUpper': '' }));
841
                            ruleTextArr.push(this.translate.instant('lang.password' + rule.label));
Damien's avatar
Damien committed
842
843
844
                        }


845
                    } else if (rule.label === 'complexityNumber') {
Damien's avatar
Damien committed
846
847
848
849
                        this.passwordRules.complexityNumber.enabled = rule.enabled;
                        this.passwordRules.complexityNumber.value = rule.value;
                        if (rule.enabled) {
                            valArr.push(this.regexValidator(new RegExp('[0-9]'), { 'complexityNumber': '' }));
850
                            ruleTextArr.push(this.translate.instant('lang.password' + rule.label));
Damien's avatar
Damien committed
851
852
853
                        }


854
                    } else if (rule.label === 'complexitySpecial') {
Damien's avatar
Damien committed
855
856
857
858
                        this.passwordRules.complexitySpecial.enabled = rule.enabled;
                        this.passwordRules.complexitySpecial.value = rule.value;
                        if (rule.enabled) {
                            valArr.push(this.regexValidator(new RegExp('[^A-Za-z0-9]'), { 'complexitySpecial': '' }));
859
                            ruleTextArr.push(this.translate.instant('lang.password' + rule.label));
Damien's avatar
Damien committed
860
                        }
861
                    } else if (rule.label === 'renewal') {
Damien's avatar
Damien committed
862
863
864
                        this.passwordRules.renewal.enabled = rule.enabled;
                        this.passwordRules.renewal.value = rule.value;
                        if (rule.enabled) {