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