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';
29 /** Holds grid with access to detail page and other actions */
32 selector: 'eg-holds-grid',
33 templateUrl: 'grid.component.html'
35 export class HoldsGridComponent implements OnInit {
37 // Hide the "Holds Count" header
38 @Input() hideHoldsCount = false;
40 // If either are set/true, the pickup lib selector will display
41 @Input() initialPickupLib: number | IdlObject;
42 @Input() hidePickupLibFilter: boolean;
44 // Setting a value here puts us into "pull list" mode.
45 @Input() pullListOrg: number;
47 // If true, only retrieve holds with a Hopeless Date
48 // and enable related Actions
49 @Input() hopeless: boolean;
52 @Input() persistKey: string;
54 @Input() preFetchSetting: string;
56 @Input() printTemplate: string;
58 // Adds a Place Hold grid toolbar button that emits
59 // placeHoldRequested on click.
60 @Input() showPlaceHoldButton = false;
62 // If set, all holds are fetched on grid load and sorting/paging all
63 // happens in the client. If false, sorting and paging occur on
65 @Input() enablePreFetch: boolean;
67 // How to sort when no sort parameters have been applied
68 // via grid controls. This uses the eg-grid sort format:
69 // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
70 @Input() defaultSort: any[];
72 // To pass through to the underlying eg-grid
73 @Input() showFields: string;
75 // Display bib record summary along the top of the detail page.
76 @Input() showRecordSummary = false;
78 // If true, avoid popping up the progress dialog. Note the grid
79 // has it's own generic embedded 'loading' progress indicator.
80 @Input() noLoadProgress = false;
82 // Some default columns and actions do or don't make sense when
83 // displaying holds for a specific patron vs. e.g. a specific title.
84 @Input() patronFocused = false;
86 mode: 'list' | 'detail' | 'manage' = 'list';
91 gridDataSource: GridDataSource;
94 transferTarget: number;
95 uncancelHoldCount: number;
98 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
99 @ViewChild('progressDialog', { static: true })
100 private progressDialog: ProgressDialogComponent;
101 @ViewChild('transferDialog', { static: true })
102 private transferDialog: HoldTransferDialogComponent;
103 @ViewChild('markDamagedDialog', { static: true })
104 private markDamagedDialog: MarkDamagedDialogComponent;
105 @ViewChild('markMissingDialog', { static: true })
106 private markMissingDialog: MarkMissingDialogComponent;
107 @ViewChild('markDiscardDialog')
108 private markDiscardDialog: MarkDiscardDialogComponent;
109 @ViewChild('retargetDialog', { static: true })
110 private retargetDialog: HoldRetargetDialogComponent;
111 @ViewChild('cancelDialog', { static: true })
112 private cancelDialog: HoldCancelDialogComponent;
113 @ViewChild('manageDialog', { static: true })
114 private manageDialog: HoldManageDialogComponent;
115 @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
119 @Input() set recordId(id: number) {
121 if (this.initDone) { // reload on update
122 this.holdsGrid.reload();
126 get recordId(): number {
127 return this._recordId;
131 @Input() set patronId(id: number) {
134 this.holdsGrid.reload();
137 get patronId(): number {
138 return this._patronId;
141 // If true, show recently canceled holds only.
142 @Input() showRecentlyCanceled = false;
144 // Include holds fulfilled on or after hte provided date.
145 // If no value is passed, fulfilled holds are not displayed.
146 _showFulfilledSince: Date;
147 @Input() set showFulfilledSince(show: Date) {
148 this._showFulfilledSince = show;
149 if (this.initDone) { // reload on update
150 this.holdsGrid.reload();
153 get showFulfilledSince(): Date {
154 return this._showFulfilledSince;
158 cellTextGenerator: GridCellTextGenerator;
160 // Include holds marked Hopeless on or after this date.
161 _showHopelessAfter: Date;
162 @Input() set showHopelessAfter(show: Date) {
163 this._showHopelessAfter = show;
164 if (this.initDone) { // reload on update
165 this.holdsGrid.reload();
169 // Include holds marked Hopeless on or before this date.
170 _showHopelessBefore: Date;
171 @Input() set showHopelessBefore(show: Date) {
172 this._showHopelessBefore = show;
173 if (this.initDone) { // reload on update
174 this.holdsGrid.reload();
178 // Notify the caller the place hold button was clicked.
179 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
182 private ngLocation: Location,
183 private net: NetService,
184 private org: OrgService,
185 private store: ServerStoreService,
186 private auth: AuthService,
187 private printer: PrintService,
188 private holdings: HoldingsService
190 this.gridDataSource = new GridDataSource();
191 this.enablePreFetch = null;
195 this.initDone = true;
196 this.pickupLib = this.org.get(this.initialPickupLib);
198 if (this.preFetchSetting) {
199 this.store.getItem(this.preFetchSetting).then(
200 applied => this.enablePreFetch = Boolean(applied)
203 this.enablePreFetch = false;
206 if (!this.defaultSort) {
207 if (this.pullListOrg) {
210 {name: 'copy_location_order_position', dir: 'asc'},
211 {name: 'acpl_name', dir: 'asc'},
212 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
213 {name: 'cn_label_sortkey', dir: 'asc'},
214 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
218 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
222 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
224 if (!this.hidePickupLibFilter && !this.plCompLoaded) {
225 // When the pickup lib selector is active, avoid any
226 // data fetches until it has settled on a default value.
227 // Once the final value is applied, its onchange will
228 // fire and we'll be back here with plCompLoaded=true.
232 sort = sort.length > 0 ? sort : this.defaultSort;
233 return this.fetchHolds(pager, sort);
236 // Text-ify function for cells that use display templates.
237 this.cellTextGenerator = {
238 title: row => row.title,
239 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
240 current_item: row => row.current_copy ? row.cp_barcode : '',
241 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
242 ucard_barcode: row => row.ucard_barcode,
243 hold_status: row => row.hold_status // TODO labels
247 // Returns true after all data/settings/etc required to render the
248 // grid have been fetched.
249 initComplete(): boolean {
250 return this.enablePreFetch !== null;
253 pickupLibChanged(org: IdlObject) {
254 this.pickupLib = org;
255 this.holdsGrid.reload();
258 pullListOrgChanged(org: IdlObject) {
259 this.pullListOrg = org.id();
260 this.holdsGrid.reload();
263 copyLocationChange(loc: IdlObject) {
264 this.copyLocation = loc ? loc.id() : null;
265 this.holdsGrid.reload();
268 preFetchHolds(apply: boolean) {
269 this.enablePreFetch = apply;
272 setTimeout(() => this.holdsGrid.reload());
275 if (this.preFetchSetting) {
277 this.store.setItem(this.preFetchSetting, apply);
281 applyFilters(): any {
283 const filters: any = {};
285 if (this.copyLocation) {
286 filters['acpl.id'] = this.copyLocation;
289 if (this.pickupLib) {
291 this.org.descendants(this.pickupLib, true);
294 if (this.pullListOrg) {
295 filters.cancel_time = null;
296 filters.capture_time = null;
297 filters.frozen = 'f';
299 // cp.* fields are set for copy-level holds even if they
300 // have no current_copy. Make sure current_copy is set.
301 filters.current_copy = {'is not': null};
303 // There are aliases for these (cp_status, cp_circ_lib),
304 // but the API complains when I use them.
305 filters['cp.status'] = {"in":{"select":{"ccs":["id"]},"from":"ccs","where":{"holdable":'t',"is_available":'t'}}};
306 filters['cp.circ_lib'] = this.pullListOrg;
307 // Avoid deleted copies AND this uses a database index on copy circ_lib where deleted is false.
308 filters['cp.deleted'] = 'f';
313 if (this._showFulfilledSince) {
314 filters.fulfillment_time = this._showFulfilledSince.toISOString();
316 filters.fulfillment_time = null;
321 filters['hopeless_holds'] = {
322 'start_date' : this._showHopelessAfter
324 // FIXME -- consistency desired, string or object
325 typeof this._showHopelessAfter === 'object'
326 ? this._showHopelessAfter.toISOString()
327 : this._showHopelessAfter
329 : '1970-01-01T00:00:00.000Z',
330 'end_date' : this._showHopelessBefore
332 // FIXME -- consistency desired, string or object
333 typeof this._showHopelessBefore === 'object'
334 ? this._showHopelessBefore.toISOString()
335 : this._showHopelessBefore
337 : (new Date()).toISOString()
342 filters.record_id = this.recordId;
346 filters.usr_id = this.patronId;
352 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
354 // We need at least one filter.
355 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
359 const filters = this.applyFilters();
361 const orderBy: any = [];
362 if (sort.length > 0) {
363 sort.forEach(obj => {
364 const subObj: any = {};
365 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
366 orderBy.push(subObj);
370 const limit = this.enablePreFetch ? null : pager.limit;
371 const offset = this.enablePreFetch ? 0 : pager.offset;
372 const options: any = {};
373 if (this.showRecentlyCanceled) {
374 options.recently_canceled = true;
376 filters.cancel_time = null;
379 let observer: Observer<any>;
380 const observable = new Observable(obs => observer = obs);
382 if (!this.noLoadProgress) {
383 // Note remaining dialog actions have no impact
384 this.progressDialog.open();
387 this.progressDialog.update({value: 0, max: 1});
393 'open-ils.circ.hold.wide_hash.stream',
394 this.auth.token(), filters, orderBy, limit, offset, options
398 if (first) { // First response is the hold count.
399 this.holdsCount = Number(holdData);
402 } else { // Subsequent responses are hold data blobs
404 this.progressDialog.update(
405 {value: ++loadCount, max: this.holdsCount});
407 observer.next(holdData);
411 this.progressDialog.close();
415 this.progressDialog.close();
423 metaRecordHoldsSelected(rows: IdlObject[]) {
425 rows.forEach( row => {
426 if (row.hold_type === 'M') {
433 nonTitleHoldsSelected(rows: IdlObject[]) {
435 rows.forEach( row => {
436 if (row.hold_type !== 'T') {
443 showDetails(rows: any[]) {
444 this.showDetail(rows[0]);
447 showHoldsForTitle(rows: any[]) {
448 if (rows.length === 0) { return; }
450 const url = this.ngLocation.prepareExternalUrl(
451 `/staff/catalog/record/${rows[0].record_id}/holds`);
453 window.open(url, '_blank');
456 showDetail(row: any) {
458 this.mode = 'detail';
459 this.detailHold = row;
463 showManager(rows: any[]) {
465 this.mode = 'manage';
466 this.editHolds = rows.map(r => r.id);
470 handleModify(rowsModified: boolean) {
474 // give the grid a chance to render then ask it to reload
475 setTimeout(() => this.holdsGrid.reload());
481 showRecentCircs(rows: any[]) {
482 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
483 copyIds.forEach( copyId => {
485 '/eg/staff/cat/item/' + copyId + '/circ_list';
486 window.open(url, '_blank');
490 showPatron(rows: any[]) {
491 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
492 usrIds.forEach( usrId => {
494 '/eg/staff/circ/patron/' + usrId + '/checkout';
495 window.open(url, '_blank');
499 showOrder(rows: any[]) {
500 // Doesn't work in Typescript currently without compiler option:
501 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
502 const bibIds = Array.from(
503 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
504 bibIds.forEach( bibId => {
506 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
507 window.open(url, '_blank');
511 addVolume(rows: any[]) {
512 const bibIds = Array.from(
513 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
514 bibIds.forEach( bibId => {
515 this.holdings.spawnAddHoldingsUi(bibId);
519 showTitle(rows: any[]) {
520 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
521 bibIds.forEach( bibId => {
522 // const url = '/eg/staff/cat/catalog/record/' + bibId;
523 const url = '/eg2/staff/catalog/record/' + bibId;
524 window.open(url, '_blank');
528 showManageDialog(rows: any[]) {
529 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
530 if (holdIds.length > 0) {
531 this.manageDialog.holdIds = holdIds;
532 this.manageDialog.open({size: 'lg'}).subscribe(
535 this.holdsGrid.reload();
542 showTransferDialog(rows: any[]) {
543 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
544 if (holdIds.length > 0) {
545 this.transferDialog.holdIds = holdIds;
546 this.transferDialog.open({}).subscribe(
549 this.holdsGrid.reload();
556 async showMarkDamagedDialog(rows: any[]) {
557 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
558 if (copyIds.length === 0) { return; }
560 let rowsModified = false;
562 const markNext = async(ids: number[]) => {
563 if (ids.length === 0) {
564 return Promise.resolve();
567 this.markDamagedDialog.copyId = ids.pop();
568 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
570 if (ok) { rowsModified = true; }
571 return markNext(ids);
573 dismiss => markNext(ids)
577 await markNext(copyIds);
579 this.holdsGrid.reload();
583 showMarkMissingDialog(rows: any[]) {
584 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
585 if (copyIds.length > 0) {
586 this.markMissingDialog.copyIds = copyIds;
587 this.markMissingDialog.open({}).subscribe(
590 this.holdsGrid.reload();
597 showMarkDiscardDialog(rows: any[]) {
598 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
599 if (copyIds.length > 0) {
600 this.markDiscardDialog.copyIds = copyIds;
601 this.markDiscardDialog.open({}).subscribe(
604 this.holdsGrid.reload();
612 showRetargetDialog(rows: any[]) {
613 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
614 if (holdIds.length > 0) {
615 this.retargetDialog.holdIds = holdIds;
616 this.retargetDialog.open({}).subscribe(
619 this.holdsGrid.reload();
626 showCancelDialog(rows: any[]) {
627 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
628 if (holdIds.length > 0) {
629 this.cancelDialog.holdIds = holdIds;
630 this.cancelDialog.open({}).subscribe(
633 this.holdsGrid.reload();
640 showUncancelDialog(rows: any[]) {
641 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
642 if (holdIds.length === 0) { return; }
643 this.uncancelHoldCount = holdIds.length;
645 this.uncancelDialog.open().subscribe(confirmed => {
646 if (!confirmed) { return; }
647 this.progressDialog.open();
649 from(holdIds).pipe(concatMap(holdId => {
650 return this.net.request(
652 'open-ils.circ.hold.uncancel',
653 this.auth.token(), holdId
657 if (Number(resp) !== 1) {
658 console.error('Failed uncanceling hold', resp);
663 this.progressDialog.close();
664 this.holdsGrid.reload();
671 // Request a page with no limit to get all of the wide holds for
672 // printing. Call requestPage() directly instead of grid.reload()
673 // since we may already have the data.
675 const pager = new Pager();
679 if (this.gridDataSource.sort.length === 0) {
680 this.gridDataSource.sort = this.defaultSort;
683 this.gridDataSource.requestPage(pager).then(() => {
684 if (this.gridDataSource.data.length > 0) {
686 templateName: this.printTemplate || 'holds_for_bib',
687 contextData: this.gridDataSource.data,
688 printContext: 'default'
694 isCopyHold(holdData: any): boolean {
695 if (holdData && holdData.hold_type) {
696 return holdData.hold_type.match(/C|R|F/) !== null;