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, GridColumn, 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'
38 export class HoldsGridComponent implements OnInit {
40 // Hide the "Holds Count" header
41 @Input() hideHoldsCount = false;
43 // If either are set/true, the pickup lib selector will display
44 @Input() initialPickupLib: number | IdlObject;
45 @Input() hidePickupLibFilter: boolean;
47 // Setting a value here puts us into "pull list" mode.
48 @Input() pullListOrg: number;
50 // If true, only retrieve holds with a Hopeless Date
51 // and enable related Actions
52 @Input() hopeless: boolean;
55 @Input() persistKey: string;
57 @Input() preFetchSetting: string;
59 @Input() printTemplate: string;
61 // Adds a Place Hold grid toolbar button that emits
62 // placeHoldRequested on click.
63 @Input() showPlaceHoldButton = false;
65 // If set, all holds are fetched on grid load and sorting/paging all
66 // happens in the client. If false, sorting and paging occur on
68 @Input() enablePreFetch: boolean;
70 // How to sort when no sort parameters have been applied
71 // via grid controls. This uses the eg-grid sort format:
72 // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
73 @Input() defaultSort: any[];
75 // To pass through to the underlying eg-grid
76 @Input() showFields: string;
78 // Display bib record summary along the top of the detail page.
79 @Input() showRecordSummary = false;
81 // If true, avoid popping up the progress dialog. Note the grid
82 // has it's own generic embedded 'loading' progress indicator.
83 @Input() noLoadProgress = false;
85 // Some default columns and actions do or don't make sense when
86 // displaying holds for a specific patron vs. e.g. a specific title.
87 @Input() patronFocused = false;
89 mode: 'list' | 'detail' | 'manage' = 'list';
94 gridDataSource: GridDataSource;
97 transferTarget: number;
98 uncancelHoldCount: number;
99 copyLocationClass?: string;
100 copyLocationEntries: ComboboxEntry[] = [];
101 copyLocationIds: number[] = [];
103 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
104 @ViewChild('progressDialog', { static: true })
105 private progressDialog: ProgressDialogComponent;
106 @ViewChild('transferDialog', { static: true })
107 private transferDialog: HoldTransferDialogComponent;
108 @ViewChild('markDamagedDialog', { static: true })
109 private markDamagedDialog: MarkDamagedDialogComponent;
110 @ViewChild('markMissingDialog', { static: true })
111 private markMissingDialog: MarkMissingDialogComponent;
112 @ViewChild('markDiscardDialog')
113 private markDiscardDialog: MarkDiscardDialogComponent;
114 @ViewChild('retargetDialog', { static: true })
115 private retargetDialog: HoldRetargetDialogComponent;
116 @ViewChild('cancelDialog', { static: true })
117 private cancelDialog: HoldCancelDialogComponent;
118 @ViewChild('manageDialog', { static: true })
119 private manageDialog: HoldManageDialogComponent;
120 @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
121 @ViewChild('copyLocationsDialog')
122 private copyLocationsDialog: HoldCopyLocationsDialogComponent;
123 @ViewChild('clearCopyLocationsDialog')
124 private clearCopyLocationsDialog: ConfirmDialogComponent;
125 @ViewChild('pullPickupLibFilter')
126 private pullPickupLibFilter: OrgSelectComponent;
130 @Input() set recordId(id: number) {
132 if (this.initDone) { // reload on update
133 this.holdsGrid.reload();
137 get recordId(): number {
138 return this._recordId;
142 @Input() set patronId(id: number) {
145 this.holdsGrid.reload();
148 get patronId(): number {
149 return this._patronId;
152 // If true, show recently canceled holds only.
153 @Input() showRecentlyCanceled = false;
155 // Include holds fulfilled on or after hte provided date.
156 // If no value is passed, fulfilled holds are not displayed.
157 _showFulfilledSince: Date;
158 @Input() set showFulfilledSince(show: Date) {
159 this._showFulfilledSince = show;
160 if (this.initDone) { // reload on update
161 this.holdsGrid.reload();
164 get showFulfilledSince(): Date {
165 return this._showFulfilledSince;
169 cellTextGenerator: GridCellTextGenerator;
171 // Include holds marked Hopeless on or after this date.
172 _showHopelessAfter: Date;
173 @Input() set showHopelessAfter(show: Date) {
174 this._showHopelessAfter = show;
175 if (this.initDone) { // reload on update
176 this.holdsGrid.reload();
180 // Include holds marked Hopeless on or before this date.
181 _showHopelessBefore: Date;
182 @Input() set showHopelessBefore(show: Date) {
183 this._showHopelessBefore = show;
184 if (this.initDone) { // reload on update
185 this.holdsGrid.reload();
189 // Notify the caller the place hold button was clicked.
190 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
193 private ngLocation: Location,
194 private net: NetService,
195 private org: OrgService,
196 private store: ServerStoreService,
197 private auth: AuthService,
198 private printer: PrintService,
199 private holdings: HoldingsService
201 this.gridDataSource = new GridDataSource();
202 this.enablePreFetch = null;
206 this.initDone = true;
207 this.pickupLib = this.org.get(this.initialPickupLib);
209 if (this.preFetchSetting) {
210 this.store.getItem(this.preFetchSetting).then(
211 applied => this.enablePreFetch = Boolean(applied)
214 this.enablePreFetch = false;
217 if (!this.defaultSort) {
218 if (this.pullListOrg) {
221 {name: 'copy_location_order_position', dir: 'asc'},
222 {name: 'acpl_name', dir: 'asc'},
223 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
224 {name: 'cn_label_sortkey', dir: 'asc'},
225 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
229 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
233 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
235 if (!this.hidePickupLibFilter || this.pullListOrg) {
236 // When the pickup lib selector is active, avoid any
237 // data fetches until it has settled on a default value.
238 // Once the final value is applied, its onchange will
239 // fire and we'll be back here with plCompLoaded=true.
240 if (!this.plCompLoaded) return of([]);
243 sort = sort.length > 0 ? sort : this.defaultSort;
244 return this.fetchHolds(pager, sort);
247 // Text-ify function for cells that use display templates.
248 this.cellTextGenerator = {
249 title: row => row.title,
250 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
251 current_item: row => row.current_copy ? row.cp_barcode : '',
252 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
253 ucard_barcode: row => row.ucard_barcode,
254 hold_status: row => row.hold_status // TODO labels
257 if (this.pullListOrg) {
258 this.store.getItem('eg.holds.pull_list_filters').then(data => {
260 this.copyLocationClass = data.copyLocationClass;
261 this.copyLocationEntries = data.copyLocationEntries;
262 this.copyLocationIds = data.copyLocationIds;
263 if (data.pickupLib) {
264 this.pickupLib = this.org.get(data.pickupLib);
267 this.copyLocationClass = 'acpl';
273 // Returns true after all data/settings/etc required to render the
274 // grid have been fetched.
275 initComplete(): boolean {
276 return this.enablePreFetch !== null;
279 pickupLibChanged(org: IdlObject) {
280 this.pickupLib = org;
281 this.holdsGrid.reload();
284 pullPickupLibLoaded(): void {
285 this.plCompLoaded = true;
286 this.holdsGrid.reload();
289 resetPullPickupLibFilter(): void {
290 if (this.pickupLib) {
291 this.pullPickupLibFilter.reset();
295 pullPickupLibChanged(org: IdlObject): void {
296 if (org?.id() !== this.pickupLib?.id()) {
297 this.pickupLib = org;
298 this.savePullFilterSettings();
299 this.holdsGrid.reload();
303 openCopyLocationsDialog(): void {
304 this.copyLocationsDialog.init();
305 this.copyLocationsDialog.open({size: 'lg'}).subscribe(
306 ([fmClass, entries, ids]) => {
307 this.copyLocationClass = fmClass;
308 this.copyLocationEntries = entries;
309 this.copyLocationIds = ids;
310 this.savePullFilterSettings();
311 this.holdsGrid.reload();
316 clearCopyLocations(): void {
317 if (!this.copyLocationEntries.length) return;
318 this.clearCopyLocationsDialog.open().subscribe(data => {
320 this.copyLocationClass = 'acpl';
321 this.copyLocationEntries = [];
322 this.copyLocationIds = [];
323 this.savePullFilterSettings();
324 this.holdsGrid.reload();
329 pullListSettingsLoaded(): boolean {
330 return !!this.copyLocationClass;
333 savePullFilterSettings(): void {
334 this.store.setItem('eg.holds.pull_list_filters', {
335 copyLocationClass: this.copyLocationClass,
336 copyLocationEntries: this.copyLocationEntries,
337 copyLocationIds: this.copyLocationIds,
338 pickupLib: this.pickupLib ? +this.pickupLib.id() : undefined
342 pullListOrgChanged(org: IdlObject): void {
343 if (org && +org.id() !== +this.pullListOrg) {
344 this.pullListOrg = org.id();
345 this.holdsGrid.reload();
349 preFetchHolds(apply: boolean) {
350 this.enablePreFetch = apply;
353 setTimeout(() => this.holdsGrid.reload());
356 if (this.preFetchSetting) {
358 this.store.setItem(this.preFetchSetting, apply);
362 applyFilters(): any {
364 const filters: any = {};
366 if (this.copyLocationIds.length) {
367 filters['acpl.id'] = this.copyLocationIds;
370 if (this.pickupLib) {
372 this.org.descendants(this.pickupLib, true);
375 if (this.pullListOrg) {
376 filters.cancel_time = null;
377 filters.capture_time = null;
378 filters.frozen = 'f';
380 // cp.* fields are set for copy-level holds even if they
381 // have no current_copy. Make sure current_copy is set.
382 filters.current_copy = {'is not': null};
384 // There are aliases for these (cp_status, cp_circ_lib),
385 // but the API complains when I use them.
386 filters['cp.status'] = {"in":{"select":{"ccs":["id"]},"from":"ccs","where":{"holdable":'t',"is_available":'t'}}};
387 filters['cp.circ_lib'] = this.pullListOrg;
388 // Avoid deleted copies AND this uses a database index on copy circ_lib where deleted is false.
389 filters['cp.deleted'] = 'f';
394 if (this._showFulfilledSince) {
395 filters.fulfillment_time = this._showFulfilledSince.toISOString();
397 filters.fulfillment_time = null;
402 filters['hopeless_holds'] = {
403 'start_date' : this._showHopelessAfter
405 // FIXME -- consistency desired, string or object
406 typeof this._showHopelessAfter === 'object'
407 ? this._showHopelessAfter.toISOString()
408 : this._showHopelessAfter
410 : '1970-01-01T00:00:00.000Z',
411 'end_date' : this._showHopelessBefore
413 // FIXME -- consistency desired, string or object
414 typeof this._showHopelessBefore === 'object'
415 ? this._showHopelessBefore.toISOString()
416 : this._showHopelessBefore
418 : (new Date()).toISOString()
423 filters.record_id = this.recordId;
427 filters.usr_id = this.patronId;
433 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
435 // We need at least one filter.
436 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
440 const filters = this.applyFilters();
442 const orderBy: any = [];
443 if (sort.length > 0) {
444 sort.forEach(obj => {
445 const subObj: any = {};
446 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
447 orderBy.push(subObj);
451 const limit = this.enablePreFetch ? null : pager.limit;
452 const offset = this.enablePreFetch ? 0 : pager.offset;
453 const options: any = {};
454 if (this.showRecentlyCanceled) {
455 options.recently_canceled = true;
457 filters.cancel_time = null;
460 let observer: Observer<any>;
461 const observable = new Observable(obs => observer = obs);
463 if (!this.noLoadProgress) {
464 // Note remaining dialog actions have no impact
465 this.progressDialog.open();
468 this.progressDialog.update({value: 0, max: 1});
474 'open-ils.circ.hold.wide_hash.stream',
475 this.auth.token(), filters, orderBy, limit, offset, options
479 if (first) { // First response is the hold count.
480 this.holdsCount = Number(holdData);
483 } else { // Subsequent responses are hold data blobs
485 this.progressDialog.update(
486 {value: ++loadCount, max: this.holdsCount});
488 observer.next(holdData);
492 this.progressDialog.close();
496 this.progressDialog.close();
504 metaRecordHoldsSelected(rows: IdlObject[]) {
506 rows.forEach( row => {
507 if (row.hold_type === 'M') {
514 nonTitleHoldsSelected(rows: IdlObject[]) {
516 rows.forEach( row => {
517 if (row.hold_type !== 'T') {
524 showDetails(rows: any[]) {
525 this.showDetail(rows[0]);
528 showHoldsForTitle(rows: any[]) {
529 if (rows.length === 0) { return; }
531 const url = this.ngLocation.prepareExternalUrl(
532 `/staff/catalog/record/${rows[0].record_id}/holds`);
534 window.open(url, '_blank');
537 showDetail(row: any) {
539 this.mode = 'detail';
540 this.detailHold = row;
544 showManager(rows: any[]) {
546 this.mode = 'manage';
547 this.editHolds = rows.map(r => r.id);
551 handleModify(rowsModified: boolean) {
555 // give the grid a chance to render then ask it to reload
556 setTimeout(() => this.holdsGrid.reload());
562 showRecentCircs(rows: any[]) {
563 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
564 copyIds.forEach( copyId => {
566 '/eg/staff/cat/item/' + copyId + '/circ_list';
567 window.open(url, '_blank');
571 showPatron(rows: any[]) {
572 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
573 usrIds.forEach( usrId => {
575 '/eg/staff/circ/patron/' + usrId + '/checkout';
576 window.open(url, '_blank');
580 showOrder(rows: any[]) {
581 // Doesn't work in Typescript currently without compiler option:
582 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
583 const bibIds = Array.from(
584 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
585 bibIds.forEach( bibId => {
587 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
588 window.open(url, '_blank');
592 addVolume(rows: any[]) {
593 const bibIds = Array.from(
594 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
595 bibIds.forEach( bibId => {
596 this.holdings.spawnAddHoldingsUi(bibId);
600 showTitle(rows: any[]) {
601 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
602 bibIds.forEach( bibId => {
603 // const url = '/eg/staff/cat/catalog/record/' + bibId;
604 const url = '/eg2/staff/catalog/record/' + bibId;
605 window.open(url, '_blank');
609 showManageDialog(rows: any[]) {
610 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
611 if (holdIds.length > 0) {
612 this.manageDialog.holdIds = holdIds;
613 this.manageDialog.open({size: 'lg'}).subscribe(
616 this.holdsGrid.reload();
623 showTransferDialog(rows: any[]) {
624 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
625 if (holdIds.length > 0) {
626 this.transferDialog.holdIds = holdIds;
627 this.transferDialog.open({}).subscribe(
630 this.holdsGrid.reload();
637 async showMarkDamagedDialog(rows: any[]) {
638 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
639 if (copyIds.length === 0) { return; }
641 let rowsModified = false;
643 const markNext = async(ids: number[]) => {
644 if (ids.length === 0) {
645 return Promise.resolve();
648 this.markDamagedDialog.copyId = ids.pop();
649 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
651 if (ok) { rowsModified = true; }
652 return markNext(ids);
654 dismiss => markNext(ids)
658 await markNext(copyIds);
660 this.holdsGrid.reload();
664 showMarkMissingDialog(rows: any[]) {
665 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
666 if (copyIds.length > 0) {
667 this.markMissingDialog.copyIds = copyIds;
668 this.markMissingDialog.open({}).subscribe(
671 this.holdsGrid.reload();
678 showMarkDiscardDialog(rows: any[]) {
679 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
680 if (copyIds.length > 0) {
681 this.markDiscardDialog.copyIds = copyIds;
682 this.markDiscardDialog.open({}).subscribe(
685 this.holdsGrid.reload();
693 showRetargetDialog(rows: any[]) {
694 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
695 if (holdIds.length > 0) {
696 this.retargetDialog.holdIds = holdIds;
697 this.retargetDialog.open({}).subscribe(
700 this.holdsGrid.reload();
707 showCancelDialog(rows: any[]) {
708 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
709 if (holdIds.length > 0) {
710 this.cancelDialog.holdIds = holdIds;
711 this.cancelDialog.open({}).subscribe(
714 this.holdsGrid.reload();
721 showUncancelDialog(rows: any[]) {
722 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
723 if (holdIds.length === 0) { return; }
724 this.uncancelHoldCount = holdIds.length;
726 this.uncancelDialog.open().subscribe(confirmed => {
727 if (!confirmed) { return; }
728 this.progressDialog.open();
730 from(holdIds).pipe(concatMap(holdId => {
731 return this.net.request(
733 'open-ils.circ.hold.uncancel',
734 this.auth.token(), holdId
738 if (Number(resp) !== 1) {
739 console.error('Failed uncanceling hold', resp);
744 this.progressDialog.close();
745 this.holdsGrid.reload();
752 // Request a page with no limit to get all of the wide holds for
753 // printing. Call requestPage() directly instead of grid.reload()
754 // since we may already have the data.
756 const pager = new Pager();
760 if (this.gridDataSource.sort.length === 0) {
761 this.gridDataSource.sort = this.defaultSort;
764 this.gridDataSource.requestPage(pager).then(() => {
765 if (this.gridDataSource.data.length > 0) {
767 templateName: this.printTemplate || 'holds_for_bib',
768 contextData: this.gridDataSource.data,
769 printContext: 'default'
775 isCopyHold(holdData: any): boolean {
776 if (holdData && holdData.hold_type) {
777 return holdData.hold_type.match(/C|R|F/) !== null;