1 import {Component, OnInit, Input, Output, EventEmitter, ViewChild} from '@angular/core';
2 import {Location} from '@angular/common';
3 import {Observable, Observer, of, from} from 'rxjs';
4 import {concatMap} from 'rxjs/operators';
5 import {IdlObject} from '@eg/core/idl.service';
6 import {NetService} from '@eg/core/net.service';
7 import {OrgService} from '@eg/core/org.service';
8 import {AuthService} from '@eg/core/auth.service';
9 import {Pager} from '@eg/share/util/pager';
10 import {ServerStoreService} from '@eg/core/server-store.service';
11 import {GridDataSource, GridCellTextGenerator} from '@eg/share/grid/grid';
12 import {GridComponent} from '@eg/share/grid/grid.component';
13 import {ProgressDialogComponent} from '@eg/share/dialog/progress.component';
14 import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component';
15 import {MarkDamagedDialogComponent
16 } from '@eg/staff/share/holdings/mark-damaged-dialog.component';
17 import {MarkMissingDialogComponent
18 } from '@eg/staff/share/holdings/mark-missing-dialog.component';
19 import {MarkDiscardDialogComponent
20 } from '@eg/staff/share/holdings/mark-discard-dialog.component';
21 import {HoldRetargetDialogComponent
22 } from '@eg/staff/share/holds/retarget-dialog.component';
23 import {HoldTransferDialogComponent} from './transfer-dialog.component';
24 import {HoldCancelDialogComponent} from './cancel-dialog.component';
25 import {HoldManageDialogComponent} from './manage-dialog.component';
26 import {PrintService} from '@eg/share/print/print.service';
27 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
28 import {OrgSelectComponent} from '@eg/share/org-select/org-select.component';
29 import {ComboboxEntry} from '@eg/share/combobox/combobox.component';
30 import {HoldCopyLocationsDialogComponent} from './copy-locations-dialog.component';
32 /** Holds grid with access to detail page and other actions */
35 selector: 'eg-holds-grid',
36 templateUrl: 'grid.component.html',
37 styles: ['.input-group > .form-control { width: auto; flex-grow: 0; }']
39 export class HoldsGridComponent implements OnInit {
41 // Hide the "Holds Count" header
42 @Input() hideHoldsCount = false;
44 // If either are set/true, the pickup lib selector will display
45 @Input() initialPickupLib: number | IdlObject;
46 @Input() hidePickupLibFilter: boolean;
48 // Setting a value here puts us into "pull list" mode.
49 @Input() pullListOrg: number;
51 // If true, only retrieve holds with a Hopeless Date
52 // and enable related Actions
53 @Input() hopeless: boolean;
56 @Input() persistKey: string;
58 @Input() preFetchSetting: string;
60 @Input() printTemplate: string;
62 // Adds a Place Hold grid toolbar button that emits
63 // placeHoldRequested on click.
64 @Input() showPlaceHoldButton = false;
66 // If set, all holds are fetched on grid load and sorting/paging all
67 // happens in the client. If false, sorting and paging occur on
69 @Input() enablePreFetch: boolean;
71 // How to sort when no sort parameters have been applied
72 // via grid controls. This uses the eg-grid sort format:
73 // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
74 @Input() defaultSort: any[];
76 // To pass through to the underlying eg-grid
77 @Input() showFields: string;
79 // Display bib record summary along the top of the detail page.
80 @Input() showRecordSummary = false;
82 // If true, avoid popping up the progress dialog. Note the grid
83 // has it's own generic embedded 'loading' progress indicator.
84 @Input() noLoadProgress = false;
86 // Some default columns and actions do or don't make sense when
87 // displaying holds for a specific patron vs. e.g. a specific title.
88 @Input() patronFocused = false;
90 mode: 'list' | 'detail' | 'manage' = 'list';
95 gridDataSource: GridDataSource;
98 transferTarget: number;
99 uncancelHoldCount: number;
100 copyLocationClass?: string;
101 copyLocationEntries: ComboboxEntry[] = [];
102 copyLocationIds: number[] = [];
104 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
105 @ViewChild('progressDialog', { static: true })
106 private progressDialog: ProgressDialogComponent;
107 @ViewChild('transferDialog', { static: true })
108 private transferDialog: HoldTransferDialogComponent;
109 @ViewChild('markDamagedDialog', { static: true })
110 private markDamagedDialog: MarkDamagedDialogComponent;
111 @ViewChild('markMissingDialog', { static: true })
112 private markMissingDialog: MarkMissingDialogComponent;
113 @ViewChild('markDiscardDialog')
114 private markDiscardDialog: MarkDiscardDialogComponent;
115 @ViewChild('retargetDialog', { static: true })
116 private retargetDialog: HoldRetargetDialogComponent;
117 @ViewChild('cancelDialog', { static: true })
118 private cancelDialog: HoldCancelDialogComponent;
119 @ViewChild('manageDialog', { static: true })
120 private manageDialog: HoldManageDialogComponent;
121 @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
122 @ViewChild('copyLocationsDialog')
123 private copyLocationsDialog: HoldCopyLocationsDialogComponent;
124 @ViewChild('clearCopyLocationsDialog')
125 private clearCopyLocationsDialog: ConfirmDialogComponent;
126 @ViewChild('pullPickupLibFilter')
127 private pullPickupLibFilter: OrgSelectComponent;
131 @Input() set recordId(id: number) {
133 if (this.initDone) { // reload on update
134 this.holdsGrid.reload();
138 get recordId(): number {
139 return this._recordId;
143 @Input() set patronId(id: number) {
146 this.holdsGrid.reload();
149 get patronId(): number {
150 return this._patronId;
153 // If true, show recently canceled holds only.
154 @Input() showRecentlyCanceled = false;
156 // Include holds fulfilled on or after hte provided date.
157 // If no value is passed, fulfilled holds are not displayed.
158 _showFulfilledSince: Date;
159 @Input() set showFulfilledSince(show: Date) {
160 this._showFulfilledSince = show;
161 if (this.initDone) { // reload on update
162 this.holdsGrid.reload();
165 get showFulfilledSince(): Date {
166 return this._showFulfilledSince;
170 cellTextGenerator: GridCellTextGenerator;
172 // Include holds marked Hopeless on or after this date.
173 _showHopelessAfter: Date;
174 @Input() set showHopelessAfter(show: Date) {
175 this._showHopelessAfter = show;
176 if (this.initDone) { // reload on update
177 this.holdsGrid.reload();
181 // Include holds marked Hopeless on or before this date.
182 _showHopelessBefore: Date;
183 @Input() set showHopelessBefore(show: Date) {
184 this._showHopelessBefore = show;
185 if (this.initDone) { // reload on update
186 this.holdsGrid.reload();
190 // Notify the caller the place hold button was clicked.
191 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
194 private ngLocation: Location,
195 private net: NetService,
196 private org: OrgService,
197 private store: ServerStoreService,
198 private auth: AuthService,
199 private printer: PrintService,
200 private holdings: HoldingsService
202 this.gridDataSource = new GridDataSource();
203 this.enablePreFetch = null;
207 this.initDone = true;
208 this.pickupLib = this.org.get(this.initialPickupLib);
210 if (this.preFetchSetting) {
211 this.store.getItem(this.preFetchSetting).then(
212 applied => this.enablePreFetch = Boolean(applied)
215 this.enablePreFetch = false;
218 if (!this.defaultSort) {
219 if (this.pullListOrg) {
222 {name: 'copy_location_order_position', dir: 'asc'},
223 {name: 'acpl_name', dir: 'asc'},
224 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
225 {name: 'cn_label_sortkey', dir: 'asc'},
226 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
230 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
234 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
236 if (!this.hidePickupLibFilter || this.pullListOrg) {
237 // When the pickup lib selector is active, avoid any
238 // data fetches until it has settled on a default value.
239 // Once the final value is applied, its onchange will
240 // fire and we'll be back here with plCompLoaded=true.
241 if (!this.plCompLoaded) {return of([]);}
244 sort = sort.length > 0 ? sort : this.defaultSort;
245 return this.fetchHolds(pager, sort);
248 // Text-ify function for cells that use display templates.
249 this.cellTextGenerator = {
250 title: row => row.title,
251 // eslint-disable-next-line eqeqeq
252 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
253 current_item: row => row.current_copy ? row.cp_barcode : '',
254 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
255 ucard_barcode: row => row.ucard_barcode,
256 status_string: row => {
257 switch (row.hold_status) {
259 return $localize`Waiting for Item`;
261 return $localize`Waiting for Capture`;
263 return $localize`In Transit`;
265 return $localize`Ready for Pickup`;
267 return $localize`Hold Shelf Delay`;
269 return $localize`Canceled`;
271 return $localize`Suspended`;
273 return $localize`Wrong Shelf`;
275 return $localize`Fulfilled`;
277 return $localize`Unknown Error`;
282 if (this.pullListOrg) {
283 this.store.getItem('eg.holds.pull_list_filters').then(data => {
285 this.copyLocationClass = data.copyLocationClass;
286 this.copyLocationEntries = data.copyLocationEntries;
287 this.copyLocationIds = data.copyLocationIds;
288 if (data.pickupLib) {
289 this.pickupLib = this.org.get(data.pickupLib);
292 this.copyLocationClass = 'acpl';
298 // Returns true after all data/settings/etc required to render the
299 // grid have been fetched.
300 initComplete(): boolean {
301 return this.enablePreFetch !== null;
304 pickupLibChanged(org: IdlObject) {
305 this.pickupLib = org;
306 this.holdsGrid.reload();
309 pullPickupLibLoaded(): void {
310 this.plCompLoaded = true;
311 this.holdsGrid.reload();
314 resetPullPickupLibFilter(): void {
315 if (this.pickupLib) {
316 this.pullPickupLibFilter.reset();
320 pullPickupLibChanged(org: IdlObject): void {
321 if (org?.id() !== this.pickupLib?.id()) {
322 this.pickupLib = org;
323 this.savePullFilterSettings();
324 this.holdsGrid.reload();
328 openCopyLocationsDialog(): void {
329 this.copyLocationsDialog.init();
330 this.copyLocationsDialog.open({size: 'lg'}).subscribe(
331 ([fmClass, entries, ids]) => {
332 this.copyLocationClass = fmClass;
333 this.copyLocationEntries = entries;
334 this.copyLocationIds = ids;
335 this.savePullFilterSettings();
336 this.holdsGrid.reload();
341 clearCopyLocations(): void {
342 if (!this.copyLocationEntries.length) {return;}
343 this.clearCopyLocationsDialog.open().subscribe(data => {
345 this.copyLocationClass = 'acpl';
346 this.copyLocationEntries = [];
347 this.copyLocationIds = [];
348 this.savePullFilterSettings();
349 this.holdsGrid.reload();
354 pullListSettingsLoaded(): boolean {
355 return !!this.copyLocationClass;
358 savePullFilterSettings(): void {
359 this.store.setItem('eg.holds.pull_list_filters', {
360 copyLocationClass: this.copyLocationClass,
361 copyLocationEntries: this.copyLocationEntries,
362 copyLocationIds: this.copyLocationIds,
363 pickupLib: this.pickupLib ? +this.pickupLib.id() : undefined
367 pullListOrgChanged(org: IdlObject): void {
368 if (org && +org.id() !== +this.pullListOrg) {
369 this.pullListOrg = org.id();
370 this.holdsGrid.reload();
374 preFetchHolds(apply: boolean) {
375 this.enablePreFetch = apply;
378 setTimeout(() => this.holdsGrid.reload());
381 if (this.preFetchSetting) {
383 this.store.setItem(this.preFetchSetting, apply);
387 applyFilters(): any {
389 const filters: any = {};
391 if (this.copyLocationIds.length) {
392 filters['acpl.id'] = this.copyLocationIds;
395 if (this.pickupLib) {
397 this.org.descendants(this.pickupLib, true);
400 if (this.pullListOrg) {
401 filters.cancel_time = null;
402 filters.capture_time = null;
403 filters.frozen = 'f';
405 // cp.* fields are set for copy-level holds even if they
406 // have no current_copy. Make sure current_copy is set.
407 filters.current_copy = {'is not': null};
409 // There are aliases for these (cp_status, cp_circ_lib),
410 // but the API complains when I use them.
411 filters['cp.status'] = {'in':{'select':{'ccs':['id']},'from':'ccs','where':{'holdable':'t','is_available':'t'}}};
412 filters['cp.circ_lib'] = this.pullListOrg;
413 // Avoid deleted copies AND this uses a database index on copy circ_lib where deleted is false.
414 filters['cp.deleted'] = 'f';
419 if (this._showFulfilledSince) {
420 filters.fulfillment_time = this._showFulfilledSince.toISOString();
422 filters.fulfillment_time = null;
427 filters['hopeless_holds'] = {
428 'start_date' : this._showHopelessAfter
430 // FIXME -- consistency desired, string or object
431 typeof this._showHopelessAfter === 'object'
432 ? this._showHopelessAfter.toISOString()
433 : this._showHopelessAfter
435 : '1970-01-01T00:00:00.000Z',
436 'end_date' : this._showHopelessBefore
438 // FIXME -- consistency desired, string or object
439 typeof this._showHopelessBefore === 'object'
440 ? this._showHopelessBefore.toISOString()
441 : this._showHopelessBefore
443 : (new Date()).toISOString()
448 filters.record_id = this.recordId;
452 filters.usr_id = this.patronId;
458 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
460 // We need at least one filter.
461 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
465 const filters = this.applyFilters();
467 const orderBy: any = [];
468 if (sort.length > 0) {
469 sort.forEach(obj => {
470 const subObj: any = {};
471 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
472 orderBy.push(subObj);
476 const limit = this.enablePreFetch ? null : pager.limit;
477 const offset = this.enablePreFetch ? 0 : pager.offset;
478 const options: any = {};
479 if (this.showRecentlyCanceled) {
480 options.recently_canceled = true;
482 filters.cancel_time = null;
485 let observer: Observer<any>;
486 const observable = new Observable(obs => observer = obs);
488 if (!this.noLoadProgress) {
489 // Note remaining dialog actions have no impact
490 this.progressDialog.open();
493 this.progressDialog.update({value: 0, max: 1});
499 'open-ils.circ.hold.wide_hash.stream',
500 this.auth.token(), filters, orderBy, limit, offset, options
504 if (first) { // First response is the hold count.
505 this.holdsCount = Number(holdData);
508 } else { // Subsequent responses are hold data blobs
510 this.progressDialog.update(
511 {value: ++loadCount, max: this.holdsCount});
513 observer.next(holdData);
517 this.progressDialog.close();
521 this.progressDialog.close();
529 metaRecordHoldsSelected(rows: IdlObject[]) {
531 rows.forEach( row => {
532 if (row.hold_type === 'M') {
539 nonTitleHoldsSelected(rows: IdlObject[]) {
541 rows.forEach( row => {
542 if (row.hold_type !== 'T') {
549 showDetails(rows: any[]) {
550 this.showDetail(rows[0]);
553 showHoldsForTitle(rows: any[]) {
554 if (rows.length === 0) { return; }
556 const url = this.ngLocation.prepareExternalUrl(
557 `/staff/catalog/record/${rows[0].record_id}/holds`);
559 window.open(url, '_blank');
562 showDetail(row: any) {
564 this.mode = 'detail';
565 this.detailHold = row;
569 showManager(rows: any[]) {
571 this.mode = 'manage';
572 this.editHolds = rows.map(r => r.id);
576 handleModify(rowsModified: boolean) {
580 // give the grid a chance to render then ask it to reload
581 setTimeout(() => this.holdsGrid.reload());
587 showRecentCircs(rows: any[]) {
588 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
589 copyIds.forEach( copyId => {
591 '/eg/staff/cat/item/' + copyId + '/circ_list';
592 window.open(url, '_blank');
596 showPatron(rows: any[]) {
597 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
598 usrIds.forEach( usrId => {
600 '/eg/staff/circ/patron/' + usrId + '/checkout';
601 window.open(url, '_blank');
605 showOrder(rows: any[]) {
606 // Doesn't work in Typescript currently without compiler option:
607 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
608 const bibIds = Array.from(
609 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
610 bibIds.forEach( bibId => {
612 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
613 window.open(url, '_blank');
617 addVolume(rows: any[]) {
618 const bibIds = Array.from(
619 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
620 bibIds.forEach( bibId => {
621 this.holdings.spawnAddHoldingsUi(bibId);
625 showTitle(rows: any[]) {
626 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
627 bibIds.forEach( bibId => {
628 // const url = '/eg/staff/cat/catalog/record/' + bibId;
629 const url = '/eg2/staff/catalog/record/' + bibId;
630 window.open(url, '_blank');
634 showManageDialog(rows: any[]) {
635 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
636 if (holdIds.length > 0) {
637 this.manageDialog.holdIds = holdIds;
638 this.manageDialog.open({size: 'lg'}).subscribe(
641 this.holdsGrid.reload();
648 showTransferDialog(rows: any[]) {
649 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
650 if (holdIds.length > 0) {
651 this.transferDialog.holdIds = holdIds;
652 this.transferDialog.open({}).subscribe(
655 this.holdsGrid.reload();
662 async showMarkDamagedDialog(rows: any[]) {
663 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
664 if (copyIds.length === 0) { return; }
666 let rowsModified = false;
668 const markNext = async(ids: number[]) => {
669 if (ids.length === 0) {
670 return Promise.resolve();
673 this.markDamagedDialog.copyId = ids.pop();
674 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
676 if (ok) { rowsModified = true; }
677 return markNext(ids);
679 (dismiss: unknown) => markNext(ids)
683 await markNext(copyIds);
685 this.holdsGrid.reload();
689 showMarkMissingDialog(rows: any[]) {
690 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
691 if (copyIds.length > 0) {
692 this.markMissingDialog.copyIds = copyIds;
693 this.markMissingDialog.open({}).subscribe(
696 this.holdsGrid.reload();
703 showMarkDiscardDialog(rows: any[]) {
704 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
705 if (copyIds.length > 0) {
706 this.markDiscardDialog.copyIds = copyIds;
707 this.markDiscardDialog.open({}).subscribe(
710 this.holdsGrid.reload();
718 showRetargetDialog(rows: any[]) {
719 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
720 if (holdIds.length > 0) {
721 this.retargetDialog.holdIds = holdIds;
722 this.retargetDialog.open({}).subscribe(
725 this.holdsGrid.reload();
732 showCancelDialog(rows: any[]) {
733 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
734 if (holdIds.length > 0) {
735 this.cancelDialog.holdIds = holdIds;
736 this.cancelDialog.open({}).subscribe(
739 this.holdsGrid.reload();
746 showUncancelDialog(rows: any[]) {
747 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
748 if (holdIds.length === 0) { return; }
749 this.uncancelHoldCount = holdIds.length;
751 this.uncancelDialog.open().subscribe(confirmed => {
752 if (!confirmed) { return; }
753 this.progressDialog.open();
755 from(holdIds).pipe(concatMap(holdId => {
756 return this.net.request(
758 'open-ils.circ.hold.uncancel',
759 this.auth.token(), holdId
761 // eslint-disable-next-line rxjs/no-nested-subscribe
764 if (Number(resp) !== 1) {
765 console.error('Failed uncanceling hold', resp);
770 this.progressDialog.close();
771 this.holdsGrid.reload();
778 // Request a page with no limit to get all of the wide holds for
779 // printing. Call requestPage() directly instead of grid.reload()
780 // since we may already have the data.
782 const pager = new Pager();
786 if (this.gridDataSource.sort.length === 0) {
787 this.gridDataSource.sort = this.defaultSort;
790 this.gridDataSource.requestPage(pager).then(() => {
791 if (this.gridDataSource.data.length > 0) {
793 templateName: this.printTemplate || 'holds_for_bib',
794 contextData: this.gridDataSource.data,
795 printContext: 'default'
801 isCopyHold(holdData: any): boolean {
802 if (holdData && holdData.hold_type) {
803 return holdData.hold_type.match(/C|R|F/) !== null;