1 import { Component, OnInit, AfterViewInit, QueryList, ViewChildren, ViewChild, OnDestroy } from '@angular/core';
2 import {FormGroup, FormControl, ValidationErrors, ValidatorFn, FormArray} from '@angular/forms';
3 import {Router, ActivatedRoute} from '@angular/router';
4 import {from, iif, Observable, of, throwError, timer, Subscription} from 'rxjs';
5 import {catchError, debounceTime, takeLast, mapTo, single, switchMap, tap} from 'rxjs/operators';
6 import {NgbCalendar, NgbTabset} from '@ng-bootstrap/ng-bootstrap';
7 import {AuthService} from '@eg/core/auth.service';
8 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
9 import {FormatService} from '@eg/core/format.service';
10 import {GridComponent} from '@eg/share/grid/grid.component';
11 import {GridDataSource, GridRowFlairEntry} from '@eg/share/grid/grid';
12 import {IdlObject} from '@eg/core/idl.service';
13 import {NetService} from '@eg/core/net.service';
14 import {PcrudService} from '@eg/core/pcrud.service';
15 import {CreateReservationDialogComponent} from './create-reservation-dialog.component';
16 import {ServerStoreService} from '@eg/core/server-store.service';
17 import {ToastService} from '@eg/share/toast/toast.service';
18 import {DateRange} from '@eg/share/daterange-select/daterange-select.component';
19 import {FmRecordEditorComponent} from '@eg/share/fm-editor/fm-editor.component';
20 import {ScheduleGridService, ScheduleRow} from './schedule-grid.service';
21 import {NoTimezoneSetComponent} from './no-timezone-set.component';
23 import * as Moment from 'moment-timezone';
25 const startOfDayIsBeforeEndOfDayValidator: ValidatorFn = (fg: FormGroup): ValidationErrors | null => {
26 const start = fg.get('startOfDay').value;
27 const end = fg.get('endOfDay').value;
28 return start !== null && end !== null &&
29 (start.hour <= end.hour) &&
30 !((start.hour === end.hour) && (start.minute >= end.minute))
32 : { startOfDayNotBeforeEndOfDay: true };
36 templateUrl: './create-reservation.component.html',
37 styles: ['#ideal-resource-barcode {min-width: 300px;}']
39 export class CreateReservationComponent implements OnInit, AfterViewInit, OnDestroy {
43 attributes: IdlObject[] = [];
45 resourceAvailabilityIcon: (row: ScheduleRow) => GridRowFlairEntry;
48 resourceBarcode: string;
50 transferable: boolean;
51 resourceOwner: number;
52 subscriptions: Subscription[] = [];
54 defaultGranularity = 30;
55 granularity: number = this.defaultGranularity;
57 scheduleSource: GridDataSource = new GridDataSource();
59 minuteStep: () => number;
60 reservationTypes: {id: string, name: string}[];
62 openTheDialog: (rows: IdlObject[]) => void;
64 resources: IdlObject[] = [];
66 setGranularity: () => void;
67 changeGranularity: ($event: ComboboxEntry) => void;
71 @ViewChild('createDialog') createDialog: CreateReservationDialogComponent;
72 @ViewChild('details') details: NgbTabset;
73 @ViewChild('noTimezoneSetDialog') noTimezoneSetDialog: NoTimezoneSetComponent;
74 @ViewChild('viewReservation') viewReservation: FmRecordEditorComponent;
75 @ViewChildren('scheduleGrid') scheduleGrids: QueryList<GridComponent>;
78 private auth: AuthService,
79 private calendar: NgbCalendar,
80 private format: FormatService,
81 private net: NetService,
82 private pcrud: PcrudService,
83 private route: ActivatedRoute,
84 private router: Router,
85 private scheduleService: ScheduleGridService,
86 private store: ServerStoreService,
87 private toast: ToastService,
92 if (!(this.format.wsOrgTimezone)) {
93 this.noTimezoneSetDialog.open();
96 const initialRangeLength = 10;
97 const defaultRange = {
98 fromDate: this.calendar.getToday(),
99 toDate: this.calendar.getNext(
100 this.calendar.getToday(), 'd', initialRangeLength)
103 this.route.paramMap.pipe(
105 this.patronId = +params.get('patron_id');
106 this.resourceBarcode = params.get('resource_barcode');
108 switchMap(params => iif(() => params.has('resource_barcode'),
109 this.handleBarcodeFromUrl$(params.get('resource_barcode')),
114 console.warn('could not find a resource with this barcode');
118 this.reservationTypes = [
119 {id: 'single', name: 'Single day reservation'},
120 {id: 'multi', name: 'Multiple day reservation'},
123 const waitToLoadResource = 800;
124 this.criteria = new FormGroup({
125 'resourceBarcode': new FormControl(this.resourceBarcode ? this.resourceBarcode : '',
127 timer(waitToLoadResource).pipe(switchMap(() =>
128 this.pcrud.search('brsrc',
129 {'barcode' : rb.value},
133 catchError(() => of({ resourceBarcode: 'No resource found with that barcode' }))
135 'resourceType': new FormControl(),
136 'startOfDay': new FormControl({hour: 9, minute: 0, second: 0}),
137 'endOfDay': new FormControl({hour: 17, minute: 0, second: 0}),
138 'idealDate': new FormControl(new Date()),
139 'idealDateRange': new FormControl(defaultRange),
140 'reservationType': new FormControl(),
141 'owningLibrary': new FormControl({primaryOrgId: this.auth.user().ws_ou(), includeDescendants: true}),
142 'selectedAttributes': new FormArray([]),
143 }, [ startOfDayIsBeforeEndOfDayValidator
146 const debouncing = 1500;
147 this.criteria.get('resourceBarcode').valueChanges
148 .pipe(debounceTime(debouncing))
149 .subscribe((barcode) => {
151 if ('INVALID' === this.criteria.get('resourceBarcode').status) {
152 this.toast.danger('No resource found with this barcode');
154 this.router.navigate(['/staff', 'booking', 'create_reservation', 'for_resource', barcode]);
158 this.subscriptions.push(
159 this.resourceType.valueChanges.pipe(
160 switchMap((value) => {
161 this.resourceBarcode = null;
163 this.resourceId = null;
164 this.attributes = [];
165 // TODO: when we upgrade to Angular 8, this can
166 // be simplified to this.selectedAttributes.clear();
167 while (this.selectedAttributes.length) {
168 this.selectedAttributes.removeAt(0);
171 return this.pcrud.search('bra', {resource_type : value.id}, {
172 order_by: 'name ASC',
174 flesh_fields: {'bra' : ['valid_values']}
177 this.attributes.push(attribute);
178 this.selectedAttributes.push(new FormControl());
185 ).subscribe(() => this.fetchData()));
187 this.criteria.get('reservationType').valueChanges.subscribe((val) => {
188 this.multiday = ('multi' === val.id);
189 this.store.setItem('eg.booking.create.multiday', this.multiday);
192 this.subscriptions.push(
193 this.owningLibraryFamily.valueChanges
194 .subscribe(() => this.resources = []));
196 this.subscriptions.push(
197 this.criteria.valueChanges
198 .subscribe(() => this.fetchData()));
200 this.store.getItem('eg.booking.create.multiday').then(multiday => {
201 if (multiday) { this.multiday = multiday; }
202 this.criteria.patchValue({reservationType:
203 this.multiday ? this.reservationTypes[1] : this.reservationTypes[0]
207 const minutesInADay = 1440;
209 this.setGranularity = () => {
210 if (this.multiday) { // multiday reservations always use day granularity
211 this.granularity = minutesInADay;
213 this.store.getItem('eg.booking.create.granularity').then(granularity => {
215 this.granularity = granularity;
217 this.granularity = this.defaultGranularity;
223 this.criteria.get('idealDate').valueChanges
224 .pipe(switchMap((date) => this.scheduleService.hoursOfOperation(date)))
225 .subscribe((hours) => this.criteria.patchValue(hours, {emitEvent: false}),
227 () => this.fetchData());
229 this.changeGranularity = ($event) => {
230 this.granularity = $event.id;
231 this.store.setItem('eg.booking.create.granularity', $event.id)
232 .then(() => this.fetchData());
235 const minutesInAnHour = 60;
237 this.minuteStep = () => {
238 return (this.granularity < minutesInAnHour) ? this.granularity : this.defaultGranularity;
241 this.resourceAvailabilityIcon = (row: ScheduleRow) => {
242 return this.scheduleService.resourceAvailabilityIcon(row, this.resources.length);
249 this.openTheDialog = (rows: IdlObject[]) => {
250 if (rows && rows.length) {
251 this.createDialog.setDefaultTimes(rows.map((row) => row['time'].clone()), this.granularity);
253 this.subscriptions.push(
254 this.createDialog.open({size: 'lg'})
255 .subscribe(() => this.fetchData())
260 fetchData = (): void => {
261 this.setGranularity();
262 this.scheduleSource.data = [];
263 let resources$ = this.scheduleService.fetchRelevantResources(
264 this.resourceType.value ? this.resourceType.value.id : null,
265 this.owningLibraries,
266 this.flattenedSelectedAttributes
268 if (this.resourceId) {
269 resources$ = from(this.resources);
275 tap((resource) => this.resources.push(resource)),
278 let range = {startTime: Moment(), endTime: Moment()};
281 range = this.scheduleService.momentizeDateRange(
283 this.format.wsOrgTimezone
286 range = this.scheduleService.momentizeDay(
290 this.format.wsOrgTimezone
293 this.scheduleSource.data = this.scheduleService.createBasicSchedule(
294 range, this.granularity);
295 return this.scheduleService.fetchReservations(range, this.resources.map(r => r.id()));
297 ).subscribe((reservation) => {
298 this.scheduleSource.data = this.scheduleService.addReservationToSchedule(
300 this.scheduleSource.data,
302 this.format.wsOrgTimezone
306 // TODO: make this into cross-field validation, and don't fetch data if true
307 invalidMultidaySettings(): boolean {
308 return (this.multiday && (!this.idealDateRange ||
309 (null == this.idealDateRange.fromDate) ||
310 (null == this.idealDateRange.toDate)));
313 handleBarcodeFromUrl$(barcode: string): Observable<any> {
314 return this.findResourceByBarcode$(barcode)
316 catchError(() => this.handleBrsrcError$(barcode)),
319 this.resourceId = resource.id();
320 this.criteria.patchValue({
321 resourceType: {id: resource.type()}},
323 this.resources = [resource];
324 this.details.select('select-resource');
331 findResourceByBarcode$(barcode: string): Observable<IdlObject> {
332 return this.pcrud.search('brsrc',
333 {'barcode' : barcode}, {'limit': 1})
337 handleBrsrcError$(barcode: string): Observable<any> {
338 return this.tryToMakeThisBookable$(barcode)
339 .pipe(switchMap(() => this.findResourceByBarcode$(barcode)),
341 this.toast.danger('No resource found with this barcode');
342 this.resourceId = -1;
343 return throwError('could not find or create a resource');
347 tryToMakeThisBookable$(barcode: string): Observable<any> {
348 return this.pcrud.search('acp',
349 {'barcode' : barcode}, {'limit': 1})
352 this.net.request( 'open-ils.booking',
353 'open-ils.booking.resources.create_from_copies',
354 this.auth.token(), [item.id()])
357 this.toast.danger('Cannot make this barcode bookable');
358 return throwError('Tried and failed to make that barcode bookable');
361 this.toast.info('Made this barcode bookable');
362 this.resourceId = response['brsrc'][0][0];
366 addDays = (days: number): void => {
367 const result = new Date(this.idealDate);
368 result.setDate(result.getDate() + days);
369 this.criteria.patchValue({idealDate: result});
372 openReservationViewer = (id: number): void => {
373 this.viewReservation.mode = 'view';
374 this.viewReservation.recId = id;
375 this.viewReservation.open({ size: 'lg' });
379 return this.criteria.get('resourceType');
381 get userStartOfDay() {
382 return this.criteria.get('startOfDay').value;
385 return this.criteria.get('endOfDay').value;
388 return this.criteria.get('idealDate').value;
390 get idealDateRange() {
391 return this.criteria.get('idealDateRange').value;
393 get owningLibraryFamily() {
394 return this.criteria.get('owningLibrary');
396 get owningLibraries() {
397 if (this.criteria.get('owningLibrary').value.orgIds) {
398 return this.criteria.get('owningLibrary').value.orgIds;
400 return [this.criteria.get('owningLibrary').value.primaryOrgId];
403 get selectedAttributes() {
404 return <FormArray>this.criteria.get('selectedAttributes');
406 get flattenedSelectedAttributes(): number[] {
407 return this.selectedAttributes.value.filter(Boolean).map((entry) => entry.id);
409 ngOnDestroy(): void {
410 this.subscriptions.forEach((subscription) => {
411 subscription.unsubscribe();