]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/validators/patron_barcode_validator.directive.ts
LP 2061136 follow-up: ng lint --fix
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / validators / patron_barcode_validator.directive.ts
1 import { Directive, forwardRef, Injectable } from '@angular/core';
2 import { NG_ASYNC_VALIDATORS, AsyncValidator, FormControl } from '@angular/forms';
3 import {NetService} from '@eg/core/net.service';
4 import {AuthService} from '@eg/core/auth.service';
5 import {EmptyError, Observable, SequenceError, of} from 'rxjs';
6 import {single, switchMap, catchError} from 'rxjs/operators';
7
8 @Injectable({providedIn: 'root'})
9 export class PatronBarcodeValidator implements AsyncValidator {
10     constructor(
11         private auth: AuthService,
12         private net: NetService) {
13     }
14
15     validate = (control: FormControl) => {
16         return this.parseActorCall(this.net.request(
17             'open-ils.actor',
18             'open-ils.actor.get_barcodes',
19             this.auth.token(),
20             this.auth.user().ws_ou(),
21             'actor', control.value.trim()));
22     };
23
24     private parseActorCall = (actorCall: Observable<any>) => {
25         return actorCall
26             .pipe(single(),
27                 switchMap(() => of(null)),
28                 catchError((err: unknown) => {
29                     if (err instanceof EmptyError) {
30                         return of({ patronBarcode: 'No patron found with that barcode' });
31                     } else if (err instanceof SequenceError) {
32                         return of({ patronBarcode: 'Barcode matches more than one patron' });
33                     }
34                 }));
35     };
36 }
37
38 @Directive({
39     selector: '[egValidPatronBarcode]',
40     providers: [{
41         provide: NG_ASYNC_VALIDATORS,
42         useExisting: forwardRef(() => PatronBarcodeValidator),
43         multi: true
44     }]
45 })
46 export class PatronBarcodeValidatorDirective {
47     constructor(
48         private pbv: PatronBarcodeValidator
49     ) { }
50
51     validate = (control: FormControl) => {
52         this.pbv.validate(control);
53     };
54 }
55