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 // If either are set/true, the pickup lib selector will display
38 @Input() initialPickupLib: number | IdlObject;
39 @Input() hidePickupLibFilter: boolean;
41 // Setting a value here puts us into "pull list" mode.
42 @Input() pullListOrg: number;
44 // If true, only retrieve holds with a Hopeless Date
45 // and enable related Actions
46 @Input() hopeless: boolean;
49 @Input() persistKey: string;
51 @Input() preFetchSetting: string;
53 @Input() printTemplate: string;
55 // Adds a Place Hold grid toolbar button that emits
56 // placeHoldRequested on click.
57 @Input() showPlaceHoldButton = false;
59 // If set, all holds are fetched on grid load and sorting/paging all
60 // happens in the client. If false, sorting and paging occur on
62 @Input() enablePreFetch: boolean;
64 // How to sort when no sort parameters have been applied
65 // via grid controls. This uses the eg-grid sort format:
66 // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
67 @Input() defaultSort: any[];
69 // To pass through to the underlying eg-grid
70 @Input() showFields: string;
72 // Display bib record summary along the top of the detail page.
73 @Input() showRecordSummary = false;
75 // If true, avoid popping up the progress dialog. Note the grid
76 // has it's own generic embedded 'loading' progress indicator.
77 @Input() noLoadProgress = false;
79 // Some default columns and actions do or don't make sense when
80 // displaying holds for a specific patron vs. e.g. a specific title.
81 @Input() patronFocused = false;
83 mode: 'list' | 'detail' | 'manage' = 'list';
88 gridDataSource: GridDataSource;
91 transferTarget: number;
92 uncancelHoldCount: number;
94 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
95 @ViewChild('progressDialog', { static: true })
96 private progressDialog: ProgressDialogComponent;
97 @ViewChild('transferDialog', { static: true })
98 private transferDialog: HoldTransferDialogComponent;
99 @ViewChild('markDamagedDialog', { static: true })
100 private markDamagedDialog: MarkDamagedDialogComponent;
101 @ViewChild('markMissingDialog', { static: true })
102 private markMissingDialog: MarkMissingDialogComponent;
103 @ViewChild('markDiscardDialog')
104 private markDiscardDialog: MarkDiscardDialogComponent;
105 @ViewChild('retargetDialog', { static: true })
106 private retargetDialog: HoldRetargetDialogComponent;
107 @ViewChild('cancelDialog', { static: true })
108 private cancelDialog: HoldCancelDialogComponent;
109 @ViewChild('manageDialog', { static: true })
110 private manageDialog: HoldManageDialogComponent;
111 @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
115 @Input() set recordId(id: number) {
117 if (this.initDone) { // reload on update
118 this.holdsGrid.reload();
122 get recordId(): number {
123 return this._recordId;
127 @Input() set patronId(id: number) {
130 this.holdsGrid.reload();
133 get patronId(): number {
134 return this._patronId;
137 // If true, show recently canceled holds only.
138 @Input() showRecentlyCanceled = false;
140 // Include holds fulfilled on or after hte provided date.
141 // If no value is passed, fulfilled holds are not displayed.
142 _showFulfilledSince: Date;
143 @Input() set showFulfilledSince(show: Date) {
144 this._showFulfilledSince = show;
145 if (this.initDone) { // reload on update
146 this.holdsGrid.reload();
149 get showFulfilledSince(): Date {
150 return this._showFulfilledSince;
154 cellTextGenerator: GridCellTextGenerator;
156 // Include holds marked Hopeless on or after this date.
157 _showHopelessAfter: Date;
158 @Input() set showHopelessAfter(show: Date) {
159 this._showHopelessAfter = show;
160 if (this.initDone) { // reload on update
161 this.holdsGrid.reload();
165 // Include holds marked Hopeless on or before this date.
166 _showHopelessBefore: Date;
167 @Input() set showHopelessBefore(show: Date) {
168 this._showHopelessBefore = show;
169 if (this.initDone) { // reload on update
170 this.holdsGrid.reload();
174 // Notify the caller the place hold button was clicked.
175 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
178 private ngLocation: Location,
179 private net: NetService,
180 private org: OrgService,
181 private store: ServerStoreService,
182 private auth: AuthService,
183 private printer: PrintService,
184 private holdings: HoldingsService
186 this.gridDataSource = new GridDataSource();
187 this.enablePreFetch = null;
191 this.initDone = true;
192 this.pickupLib = this.org.get(this.initialPickupLib);
194 if (this.preFetchSetting) {
195 this.store.getItem(this.preFetchSetting).then(
196 applied => this.enablePreFetch = Boolean(applied)
199 this.enablePreFetch = false;
202 if (!this.defaultSort) {
203 if (this.pullListOrg) {
206 {name: 'copy_location_order_position', dir: 'asc'},
207 {name: 'acpl_name', dir: 'asc'},
208 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
209 {name: 'cn_label_sortkey', dir: 'asc'},
210 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
214 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
218 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
220 if (!this.hidePickupLibFilter && !this.plCompLoaded) {
221 // When the pickup lib selector is active, avoid any
222 // data fetches until it has settled on a default value.
223 // Once the final value is applied, its onchange will
224 // fire and we'll be back here with plCompLoaded=true.
228 sort = sort.length > 0 ? sort : this.defaultSort;
229 return this.fetchHolds(pager, sort);
232 // Text-ify function for cells that use display templates.
233 this.cellTextGenerator = {
234 title: row => row.title,
235 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
236 current_item: row => row.current_copy ? row.cp_barcode : '',
237 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
238 ucard_barcode: row => row.ucard_barcode,
239 hold_status: row => row.hold_status // TODO labels
243 // Returns true after all data/settings/etc required to render the
244 // grid have been fetched.
245 initComplete(): boolean {
246 return this.enablePreFetch !== null;
249 pickupLibChanged(org: IdlObject) {
250 this.pickupLib = org;
251 this.holdsGrid.reload();
254 pullListOrgChanged(org: IdlObject) {
255 this.pullListOrg = org.id();
256 this.holdsGrid.reload();
259 preFetchHolds(apply: boolean) {
260 this.enablePreFetch = apply;
263 setTimeout(() => this.holdsGrid.reload());
266 if (this.preFetchSetting) {
268 this.store.setItem(this.preFetchSetting, apply);
272 applyFilters(): any {
274 const filters: any = {};
276 if (this.pullListOrg) {
277 filters.cancel_time = null;
278 filters.capture_time = null;
279 filters.frozen = 'f';
281 // cp.* fields are set for copy-level holds even if they
282 // have no current_copy. Make sure current_copy is set.
283 filters.current_copy = {'is not': null};
285 // There are aliases for these (cp_status, cp_circ_lib),
286 // but the API complains when I use them.
287 filters['cp.status'] = [0, 7];
288 filters['cp.circ_lib'] = this.pullListOrg;
293 if (this._showFulfilledSince) {
294 filters.fulfillment_time = this._showFulfilledSince.toISOString();
296 filters.fulfillment_time = null;
301 filters['hopeless_holds'] = {
302 'start_date' : this._showHopelessAfter
304 // FIXME -- consistency desired, string or object
305 typeof this._showHopelessAfter === 'object'
306 ? this._showHopelessAfter.toISOString()
307 : this._showHopelessAfter
309 : '1970-01-01T00:00:00.000Z',
310 'end_date' : this._showHopelessBefore
312 // FIXME -- consistency desired, string or object
313 typeof this._showHopelessBefore === 'object'
314 ? this._showHopelessBefore.toISOString()
315 : this._showHopelessBefore
317 : (new Date()).toISOString()
321 if (this.pickupLib) {
323 this.org.descendants(this.pickupLib, true);
327 filters.record_id = this.recordId;
331 filters.usr_id = this.patronId;
337 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
339 // We need at least one filter.
340 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
344 const filters = this.applyFilters();
346 const orderBy: any = [];
347 if (sort.length > 0) {
348 sort.forEach(obj => {
349 const subObj: any = {};
350 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
351 orderBy.push(subObj);
355 const limit = this.enablePreFetch ? null : pager.limit;
356 const offset = this.enablePreFetch ? 0 : pager.offset;
357 const options: any = {};
358 if (this.showRecentlyCanceled) {
359 options.recently_canceled = true;
361 filters.cancel_time = null;
364 let observer: Observer<any>;
365 const observable = new Observable(obs => observer = obs);
367 if (!this.noLoadProgress) {
368 // Note remaining dialog actions have no impact
369 this.progressDialog.open();
372 this.progressDialog.update({value: 0, max: 1});
378 'open-ils.circ.hold.wide_hash.stream',
379 this.auth.token(), filters, orderBy, limit, offset, options
383 if (first) { // First response is the hold count.
384 this.holdsCount = Number(holdData);
387 } else { // Subsequent responses are hold data blobs
389 this.progressDialog.update(
390 {value: ++loadCount, max: this.holdsCount});
392 observer.next(holdData);
396 this.progressDialog.close();
400 this.progressDialog.close();
408 metaRecordHoldsSelected(rows: IdlObject[]) {
410 rows.forEach( row => {
411 if (row.hold_type === 'M') {
418 nonTitleHoldsSelected(rows: IdlObject[]) {
420 rows.forEach( row => {
421 if (row.hold_type !== 'T') {
428 showDetails(rows: any[]) {
429 this.showDetail(rows[0]);
432 showHoldsForTitle(rows: any[]) {
433 if (rows.length === 0) { return; }
435 const url = this.ngLocation.prepareExternalUrl(
436 `/staff/catalog/record/${rows[0].record_id}/holds`);
438 window.open(url, '_blank');
441 showDetail(row: any) {
443 this.mode = 'detail';
444 this.detailHold = row;
448 showManager(rows: any[]) {
450 this.mode = 'manage';
451 this.editHolds = rows.map(r => r.id);
455 handleModify(rowsModified: boolean) {
459 // give the grid a chance to render then ask it to reload
460 setTimeout(() => this.holdsGrid.reload());
466 showRecentCircs(rows: any[]) {
467 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
468 copyIds.forEach( copyId => {
470 '/eg/staff/cat/item/' + copyId + '/circ_list';
471 window.open(url, '_blank');
475 showPatron(rows: any[]) {
476 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
477 usrIds.forEach( usrId => {
479 '/eg/staff/circ/patron/' + usrId + '/checkout';
480 window.open(url, '_blank');
484 showOrder(rows: any[]) {
485 // Doesn't work in Typescript currently without compiler option:
486 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
487 const bibIds = Array.from(
488 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
489 bibIds.forEach( bibId => {
491 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
492 window.open(url, '_blank');
496 addVolume(rows: any[]) {
497 const bibIds = Array.from(
498 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
499 bibIds.forEach( bibId => {
500 this.holdings.spawnAddHoldingsUi(bibId);
504 showTitle(rows: any[]) {
505 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
506 bibIds.forEach( bibId => {
507 // const url = '/eg/staff/cat/catalog/record/' + bibId;
508 const url = '/eg2/staff/catalog/record/' + bibId;
509 window.open(url, '_blank');
513 showManageDialog(rows: any[]) {
514 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
515 if (holdIds.length > 0) {
516 this.manageDialog.holdIds = holdIds;
517 this.manageDialog.open({size: 'lg'}).subscribe(
520 this.holdsGrid.reload();
527 showTransferDialog(rows: any[]) {
528 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
529 if (holdIds.length > 0) {
530 this.transferDialog.holdIds = holdIds;
531 this.transferDialog.open({}).subscribe(
534 this.holdsGrid.reload();
541 async showMarkDamagedDialog(rows: any[]) {
542 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
543 if (copyIds.length === 0) { return; }
545 let rowsModified = false;
547 const markNext = async(ids: number[]) => {
548 if (ids.length === 0) {
549 return Promise.resolve();
552 this.markDamagedDialog.copyId = ids.pop();
553 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
555 if (ok) { rowsModified = true; }
556 return markNext(ids);
558 dismiss => markNext(ids)
562 await markNext(copyIds);
564 this.holdsGrid.reload();
568 showMarkMissingDialog(rows: any[]) {
569 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
570 if (copyIds.length > 0) {
571 this.markMissingDialog.copyIds = copyIds;
572 this.markMissingDialog.open({}).subscribe(
575 this.holdsGrid.reload();
582 showMarkDiscardDialog(rows: any[]) {
583 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
584 if (copyIds.length > 0) {
585 this.markDiscardDialog.copyIds = copyIds;
586 this.markDiscardDialog.open({}).subscribe(
589 this.holdsGrid.reload();
597 showRetargetDialog(rows: any[]) {
598 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
599 if (holdIds.length > 0) {
600 this.retargetDialog.holdIds = holdIds;
601 this.retargetDialog.open({}).subscribe(
604 this.holdsGrid.reload();
611 showCancelDialog(rows: any[]) {
612 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
613 if (holdIds.length > 0) {
614 this.cancelDialog.holdIds = holdIds;
615 this.cancelDialog.open({}).subscribe(
618 this.holdsGrid.reload();
625 showUncancelDialog(rows: any[]) {
626 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
627 if (holdIds.length === 0) { return; }
628 this.uncancelHoldCount = holdIds.length;
630 this.uncancelDialog.open().subscribe(confirmed => {
631 if (!confirmed) { return; }
632 this.progressDialog.open();
634 from(holdIds).pipe(concatMap(holdId => {
635 return this.net.request(
637 'open-ils.circ.hold.uncancel',
638 this.auth.token(), holdId
642 if (Number(resp) !== 1) {
643 console.error('Failed uncanceling hold', resp);
648 this.progressDialog.close();
649 this.holdsGrid.reload();
656 // Request a page with no limit to get all of the wide holds for
657 // printing. Call requestPage() directly instead of grid.reload()
658 // since we may already have the data.
660 const pager = new Pager();
664 if (this.gridDataSource.sort.length === 0) {
665 this.gridDataSource.sort = this.defaultSort;
668 this.gridDataSource.requestPage(pager).then(() => {
669 if (this.gridDataSource.data.length > 0) {
671 templateName: this.printTemplate || 'holds_for_bib',
672 contextData: this.gridDataSource.data,
673 printContext: 'default'
679 isCopyHold(holdData: any): boolean {
680 return holdData.hold_type.match(/C|R|F/) !== null;