]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/booking/create-reservation-dialog.component.ts
LP1830973 Angular 8 updates
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / booking / create-reservation-dialog.component.ts
1 import {Component, Input, Output, OnInit, ViewChild, EventEmitter} from '@angular/core';
2 import {FormGroup, FormControl, Validators, ValidatorFn, ValidationErrors} from '@angular/forms';
3 import {Router} from '@angular/router';
4 import {Observable, of} from 'rxjs';
5 import {switchMap, single, startWith, tap} from 'rxjs/operators';
6 import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
7 import {AuthService} from '@eg/core/auth.service';
8 import {FormatService} from '@eg/core/format.service';
9 import {IdlObject} from '@eg/core/idl.service';
10 import {NetService} from '@eg/core/net.service';
11 import {OrgService} from '@eg/core/org.service';
12 import {PcrudService} from '@eg/core/pcrud.service';
13 import {DialogComponent} from '@eg/share/dialog/dialog.component';
14 import {PatronBarcodeValidator} from '@eg/share/validators/patron_barcode_validator.directive';
15 import {ToastService} from '@eg/share/toast/toast.service';
16 import {AlertDialogComponent} from '@eg/share/dialog/alert.component';
17 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
18 import * as Moment from 'moment-timezone';
19
20 const startTimeIsBeforeEndTimeValidator: ValidatorFn = (fg: FormGroup): ValidationErrors | null => {
21     const start = fg.get('startTime').value;
22     const end = fg.get('endTime').value;
23     return start !== null && end !== null &&
24         start.isBefore(end)
25         ? null
26         : { startTimeNotBeforeEndTime: true };
27 };
28
29 @Component({
30   selector: 'eg-create-reservation-dialog',
31   templateUrl: './create-reservation-dialog.component.html'
32 })
33
34 export class CreateReservationDialogComponent
35     extends DialogComponent implements OnInit {
36
37     @Input() targetResource: number;
38     @Input() targetResourceBarcode: string;
39     @Input() targetResourceType: ComboboxEntry;
40     @Input() patronId: number;
41     @Input() attributes: number[] = [];
42     @Input() resources: IdlObject[] = [];
43     @Output() onComplete: EventEmitter<boolean>;
44
45     create: FormGroup;
46     patron$: Observable<{first_given_name: string, second_given_name: string, family_name: string}>;
47     pickupLibId: number;
48     timezone: string = this.format.wsOrgTimezone;
49     pickupLibraryUsesDifferentTz: boolean;
50
51     public disableOrgs: () => number[];
52     addBresv$: () => Observable<any>;
53     @ViewChild('fail', { static: true }) private fail: AlertDialogComponent;
54
55     handlePickupLibChange: ($event: IdlObject) => void;
56
57     constructor(
58         private auth: AuthService,
59         private format: FormatService,
60         private net: NetService,
61         private org: OrgService,
62         private pcrud: PcrudService,
63         private router: Router,
64         private modal: NgbModal,
65         private pbv: PatronBarcodeValidator,
66         private toast: ToastService
67     ) {
68         super(modal);
69         this.onComplete = new EventEmitter<boolean>();
70     }
71
72     ngOnInit() {
73
74         this.create = new FormGroup({
75             // TODO: replace this control with a patron search form
76             // when available in the Angular client
77             'patronBarcode': new FormControl('',
78                 [Validators.required],
79                 [this.pbv.validate]
80             ),
81             'emailNotify': new FormControl(true),
82             'startTime': new FormControl(),
83             'endTime': new FormControl(),
84             'resourceList': new FormControl(),
85         }, [startTimeIsBeforeEndTimeValidator]
86         );
87         if (this.patronId) {
88             this.pcrud.search('au', {id: this.patronId}, {
89                 flesh: 1,
90                 flesh_fields: {'au': ['card']}
91             }).subscribe((usr) =>
92                 this.create.patchValue({patronBarcode: usr.card().barcode()})
93             );
94         }
95
96         this.addBresv$ = () => {
97             let selectedResourceId = this.targetResource ? [this.targetResource] : null;
98             if (!selectedResourceId &&
99                 this.resourceListSelection !== null &&
100                 'any' !== this.resourceListSelection.id) {
101                 selectedResourceId = [this.resourceListSelection.id];
102             }
103             return this.net.request(
104                 'open-ils.booking',
105                 'open-ils.booking.reservations.create',
106                 this.auth.token(),
107                 this.patronBarcode.value,
108                 this.selectedTimes,
109                 this.pickupLibId,
110                 this.targetResourceType.id,
111                 selectedResourceId,
112                 this.attributes.filter(Boolean),
113                 this.emailNotify
114             ).pipe(tap(
115                 (success) => {
116                     if (success.ilsevent) {
117                         console.warn(success);
118                         this.fail.open();
119                     } else {
120                         this.toast.success('Reservation successfully created');
121                         console.debug(success);
122                         this.close();
123                    }
124                 }, (fail) => {
125                     console.warn(fail);
126                     this.fail.open();
127                 }, () => this.onComplete.emit(true)
128             ));
129         };
130
131         this.handlePickupLibChange = ($event) => {
132             this.pickupLibId = $event.id();
133             this.org.settings('lib.timezone', this.pickupLibId).then((tz) => {
134                 this.timezone = tz['lib.timezone'] || this.format.wsOrgTimezone;
135                 this.pickupLibraryUsesDifferentTz = (tz['lib.timezone'] && (this.format.wsOrgTimezone !== tz['lib.timezone']));
136             });
137         };
138
139         this.disableOrgs = () => this.org.filterList( { canHaveVolumes : false }, true);
140
141         this.patron$ = this.patronBarcode.statusChanges.pipe(
142             startWith({first_given_name: '', second_given_name: '', family_name: ''}),
143             switchMap(() => {
144                 if ('VALID' === this.patronBarcode.status) {
145                     return this.net.request(
146                         'open-ils.actor',
147                         'open-ils.actor.get_barcodes',
148                         this.auth.token(),
149                         this.auth.user().ws_ou(),
150                         'actor', this.patronBarcode.value).pipe(
151                             single(),
152                             switchMap((result) => {
153                                 return this.pcrud.retrieve('au', result[0]['id']).pipe(
154                                     switchMap((au) => {
155                                         return of({
156                                             first_given_name: au.first_given_name(),
157                                             second_given_name: au.second_given_name(),
158                                             family_name: au.family_name()});
159                                     })
160                                 );
161                             })
162                         );
163                 } else {
164                     return of({
165                         first_given_name: '',
166                         second_given_name: '',
167                         family_name: ''
168                     });
169                 }
170             })
171         );
172     }
173
174     setDefaultTimes(times: Moment[], granularity: number) {
175         this.create.patchValue({startTime: Moment.min(times),
176         endTime: Moment.max(times).clone().add(granularity, 'minutes')
177         });
178     }
179
180     openPatronReservations = (): void => {
181         this.net.request(
182             'open-ils.actor',
183             'open-ils.actor.get_barcodes',
184             this.auth.token(),
185             this.auth.user().ws_ou(),
186             'actor', this.patronBarcode.value
187         ).subscribe((patron) => this.router.navigate(['/staff', 'booking', 'manage_reservations', 'by_patron', patron[0]['id']]));
188     }
189
190     addBresvAndOpenPatronReservations = (): void => {
191         this.addBresv$()
192         .subscribe(() => this.openPatronReservations());
193     }
194
195     get emailNotify() {
196         return this.create.get('emailNotify').value;
197     }
198
199     get patronBarcode() {
200         return this.create.get('patronBarcode');
201     }
202
203     get resourceListSelection() {
204       return this.create.get('resourceList').value;
205     }
206
207     get selectedTimes() {
208         return [this.create.get('startTime').value.toISOString(),
209             this.create.get('endTime').value.toISOString()];
210     }
211 }
212