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