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, GridCellTextGenerator} 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;
46 cellTextGenerator: GridCellTextGenerator;
49 resourceBarcode: string;
51 transferable: boolean;
52 resourceOwner: number;
53 subscriptions: Subscription[] = [];
55 defaultGranularity = 30;
56 granularity: number = this.defaultGranularity;
58 scheduleSource: GridDataSource = new GridDataSource();
60 minuteStep: () => number;
61 reservationTypes: {id: string, name: string}[];
63 openTheDialog: (rows: IdlObject[]) => void;
65 resources: IdlObject[] = [];
67 setGranularity: () => void;
68 changeGranularity: ($event: ComboboxEntry) => void;
72 @ViewChild('createDialog', { static: true }) createDialog: CreateReservationDialogComponent;
73 @ViewChild('details', { static: true }) details: NgbTabset;
74 @ViewChild('noTimezoneSetDialog', { static: true }) noTimezoneSetDialog: NoTimezoneSetComponent;
75 @ViewChild('viewReservation', { static: true }) viewReservation: FmRecordEditorComponent;
76 @ViewChildren('scheduleGrid') scheduleGrids: QueryList<GridComponent>;
79 private auth: AuthService,
80 private calendar: NgbCalendar,
81 private format: FormatService,
82 private net: NetService,
83 private pcrud: PcrudService,
84 private route: ActivatedRoute,
85 private router: Router,
86 private scheduleService: ScheduleGridService,
87 private store: ServerStoreService,
88 private toast: ToastService,
93 if (!(this.format.wsOrgTimezone)) {
94 this.noTimezoneSetDialog.open();
97 const initialRangeLength = 10;
98 const defaultRange = {
99 fromDate: this.calendar.getToday(),
100 toDate: this.calendar.getNext(
101 this.calendar.getToday(), 'd', initialRangeLength)
104 this.route.paramMap.pipe(
106 this.patronId = +params.get('patron_id');
107 this.resourceBarcode = params.get('resource_barcode');
109 switchMap(params => iif(() => params.has('resource_barcode'),
110 this.handleBarcodeFromUrl$(params.get('resource_barcode')),
115 console.warn('could not find a resource with this barcode');
119 this.reservationTypes = [
120 {id: 'single', name: 'Single day reservation'},
121 {id: 'multi', name: 'Multiple day reservation'},
124 const waitToLoadResource = 800;
125 this.criteria = new FormGroup({
126 'resourceBarcode': new FormControl(this.resourceBarcode ? this.resourceBarcode : '',
128 timer(waitToLoadResource).pipe(switchMap(() =>
129 this.pcrud.search('brsrc',
130 {'barcode' : rb.value},
134 catchError(() => of({ resourceBarcode: 'No resource found with that barcode' }))
136 'resourceType': new FormControl(),
137 'startOfDay': new FormControl({hour: 9, minute: 0, second: 0}),
138 'endOfDay': new FormControl({hour: 17, minute: 0, second: 0}),
139 'idealDate': new FormControl(new Date()),
140 'idealDateRange': new FormControl(defaultRange),
141 'reservationType': new FormControl(),
142 'owningLibrary': new FormControl({primaryOrgId: this.auth.user().ws_ou(), includeDescendants: true}),
143 'selectedAttributes': new FormArray([]),
144 }, [ startOfDayIsBeforeEndOfDayValidator
147 const debouncing = 1500;
148 this.criteria.get('resourceBarcode').valueChanges
149 .pipe(debounceTime(debouncing))
150 .subscribe((barcode) => {
152 if ('INVALID' === this.criteria.get('resourceBarcode').status) {
153 this.toast.danger('No resource found with this barcode');
155 this.router.navigate(['/staff', 'booking', 'create_reservation', 'for_resource', barcode]);
159 this.subscriptions.push(
160 this.resourceType.valueChanges.pipe(
161 switchMap((value) => {
162 this.resourceBarcode = null;
164 this.resourceId = null;
165 this.attributes = [];
166 // TODO: when we upgrade to Angular 8, this can
167 // be simplified to this.selectedAttributes.clear();
168 while (this.selectedAttributes.length) {
169 this.selectedAttributes.removeAt(0);
172 return this.pcrud.search('bra', {resource_type : value.id}, {
173 order_by: 'name ASC',
175 flesh_fields: {'bra' : ['valid_values']}
178 this.attributes.push(attribute);
179 this.selectedAttributes.push(new FormControl());
186 ).subscribe(() => this.fetchData()));
188 this.criteria.get('reservationType').valueChanges.subscribe((val) => {
189 this.multiday = ('multi' === val.id);
190 this.store.setItem('eg.booking.create.multiday', this.multiday);
193 this.subscriptions.push(
194 this.owningLibraryFamily.valueChanges
195 .subscribe(() => this.resources = []));
197 this.subscriptions.push(
198 this.criteria.valueChanges
199 .subscribe(() => this.fetchData()));
201 this.store.getItem('eg.booking.create.multiday').then(multiday => {
202 if (multiday) { this.multiday = multiday; }
203 this.criteria.patchValue({reservationType:
204 this.multiday ? this.reservationTypes[1] : this.reservationTypes[0]
208 const minutesInADay = 1440;
210 this.setGranularity = () => {
211 if (this.multiday) { // multiday reservations always use day granularity
212 this.granularity = minutesInADay;
214 this.store.getItem('eg.booking.create.granularity').then(granularity => {
216 this.granularity = granularity;
218 this.granularity = this.defaultGranularity;
224 this.criteria.get('idealDate').valueChanges
225 .pipe(switchMap((date) => this.scheduleService.hoursOfOperation(date)))
226 .subscribe((hours) => this.criteria.patchValue(hours, {emitEvent: false}),
228 () => this.fetchData());
230 this.changeGranularity = ($event) => {
231 this.granularity = $event.id;
232 this.store.setItem('eg.booking.create.granularity', $event.id)
233 .then(() => this.fetchData());
236 const minutesInAnHour = 60;
238 this.minuteStep = () => {
239 return (this.granularity < minutesInAnHour) ? this.granularity : this.defaultGranularity;
242 this.resourceAvailabilityIcon = (row: ScheduleRow) => {
243 return this.scheduleService.resourceAvailabilityIcon(row, this.resources.length);
250 this.openTheDialog = (rows: IdlObject[]) => {
251 if (rows && rows.length) {
252 this.createDialog.setDefaultTimes(rows.map((row) => row['time'].clone()), this.granularity);
254 this.subscriptions.push(
255 this.createDialog.open({size: 'lg'})
256 .subscribe(() => this.fetchData())
261 fetchData = (): void => {
262 this.setGranularity();
263 this.scheduleSource.data = [];
264 let resources$ = this.scheduleService.fetchRelevantResources(
265 this.resourceType.value ? this.resourceType.value.id : null,
266 this.owningLibraries,
267 this.flattenedSelectedAttributes
269 if (this.resourceId) {
270 resources$ = from(this.resources);
277 this.resources.push(resource);
278 this.resources.sort((a, b) =>
279 (a.barcode() > b.barcode()) ? 1 : ((b.barcode() > a.barcode()) ? -1 : 0));
283 let range = {startTime: moment(), endTime: moment()};
286 range = this.scheduleService.momentizeDateRange(
288 this.format.wsOrgTimezone
291 range = this.scheduleService.momentizeDay(
295 this.format.wsOrgTimezone
298 this.scheduleSource.data = this.scheduleService.createBasicSchedule(
299 range, this.granularity);
300 return this.scheduleService.fetchReservations(range, this.resources.map(r => r.id()));
302 ).subscribe((reservation) => {
303 this.scheduleSource.data = this.scheduleService.addReservationToSchedule(
305 this.scheduleSource.data,
307 this.format.wsOrgTimezone
311 this.cellTextGenerator = {
313 return this.multiday ? row['time'].format('LT') :
314 this.format.transform({value: row['time'], datatype: 'timestamp', datePlusTime: true});
317 this.resources.forEach(resource => {
318 this.cellTextGenerator[resource.barcode()] = row => {
319 return row.patrons[resource.barcode()] ?
320 row.patrons[resource.barcode()].map(reservation => reservation['patronLabel']).join(', ') : '';
325 // TODO: make this into cross-field validation, and don't fetch data if true
326 invalidMultidaySettings(): boolean {
327 return (this.multiday && (!this.idealDateRange ||
328 (null == this.idealDateRange.fromDate) ||
329 (null == this.idealDateRange.toDate)));
332 handleBarcodeFromUrl$(barcode: string): Observable<any> {
333 return this.findResourceByBarcode$(barcode)
335 catchError(() => this.handleBrsrcError$(barcode)),
338 this.resourceId = resource.id();
339 this.criteria.patchValue({
340 resourceType: {id: resource.type()}},
342 this.resources = [resource];
343 this.details.select('select-resource');
350 findResourceByBarcode$(barcode: string): Observable<IdlObject> {
351 return this.pcrud.search('brsrc',
352 {'barcode' : barcode}, {'limit': 1})
356 handleBrsrcError$(barcode: string): Observable<any> {
357 return this.tryToMakeThisBookable$(barcode)
358 .pipe(switchMap(() => this.findResourceByBarcode$(barcode)),
360 this.toast.danger('No resource found with this barcode');
361 this.resourceId = -1;
362 return throwError('could not find or create a resource');
366 tryToMakeThisBookable$(barcode: string): Observable<any> {
367 return this.pcrud.search('acp',
368 {'barcode' : barcode}, {'limit': 1})
371 this.net.request( 'open-ils.booking',
372 'open-ils.booking.resources.create_from_copies',
373 this.auth.token(), [item.id()])
376 this.toast.danger('Cannot make this barcode bookable');
377 return throwError('Tried and failed to make that barcode bookable');
380 this.toast.info('Made this barcode bookable');
381 this.resourceId = response['brsrc'][0][0];
385 addDays = (days: number): void => {
386 const result = new Date(this.idealDate);
387 result.setDate(result.getDate() + days);
388 this.criteria.patchValue({idealDate: result});
391 openReservationViewer = (id: number): void => {
392 this.viewReservation.mode = 'view';
393 this.viewReservation.recordId = id;
394 this.viewReservation.open({ size: 'lg' });
398 return this.criteria.get('resourceType');
400 get userStartOfDay() {
401 return this.criteria.get('startOfDay').value;
404 return this.criteria.get('endOfDay').value;
407 return this.criteria.get('idealDate').value;
409 get idealDateRange() {
410 return this.criteria.get('idealDateRange').value;
412 get owningLibraryFamily() {
413 return this.criteria.get('owningLibrary');
415 get owningLibraries() {
416 if (this.criteria.get('owningLibrary').value.orgIds) {
417 return this.criteria.get('owningLibrary').value.orgIds;
419 return [this.criteria.get('owningLibrary').value.primaryOrgId];
422 get selectedAttributes() {
423 return <FormArray>this.criteria.get('selectedAttributes');
425 get flattenedSelectedAttributes(): number[] {
426 return this.selectedAttributes.value.filter(Boolean).map((entry) => entry.id);
428 ngOnDestroy(): void {
429 this.subscriptions.forEach((subscription) => {
430 subscription.unsubscribe();