1 import {Component, OnInit, Input, Output, EventEmitter, ViewChild} from '@angular/core';
2 import {Location} from '@angular/common';
3 import {Observable, Observer, of} from 'rxjs';
4 import {IdlObject} from '@eg/core/idl.service';
5 import {NetService} from '@eg/core/net.service';
6 import {OrgService} from '@eg/core/org.service';
7 import {AuthService} from '@eg/core/auth.service';
8 import {Pager} from '@eg/share/util/pager';
9 import {ServerStoreService} from '@eg/core/server-store.service';
10 import {GridDataSource, GridColumn, GridCellTextGenerator} from '@eg/share/grid/grid';
11 import {GridComponent} from '@eg/share/grid/grid.component';
12 import {ProgressDialogComponent} from '@eg/share/dialog/progress.component';
13 import {MarkDamagedDialogComponent
14 } from '@eg/staff/share/holdings/mark-damaged-dialog.component';
15 import {MarkMissingDialogComponent
16 } from '@eg/staff/share/holdings/mark-missing-dialog.component';
17 import {MarkDiscardDialogComponent
18 } from '@eg/staff/share/holdings/mark-discard-dialog.component';
19 import {HoldRetargetDialogComponent
20 } from '@eg/staff/share/holds/retarget-dialog.component';
21 import {HoldTransferDialogComponent} from './transfer-dialog.component';
22 import {HoldCancelDialogComponent} from './cancel-dialog.component';
23 import {HoldManageDialogComponent} from './manage-dialog.component';
24 import {PrintService} from '@eg/share/print/print.service';
25 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
27 /** Holds grid with access to detail page and other actions */
30 selector: 'eg-holds-grid',
31 templateUrl: 'grid.component.html'
33 export class HoldsGridComponent implements OnInit {
35 // If either are set/true, the pickup lib selector will display
36 @Input() initialPickupLib: number | IdlObject;
37 @Input() hidePickupLibFilter: boolean;
39 // Setting a value here puts us into "pull list" mode.
40 @Input() pullListOrg: number;
42 // If true, only retrieve holds with a Hopeless Date
43 // and enable related Actions
44 @Input() hopeless: boolean;
47 @Input() persistKey: string;
49 @Input() preFetchSetting: string;
51 @Input() printTemplate: string;
53 // Adds a Place Hold grid toolbar button that emits
54 // placeHoldRequested on click.
55 @Input() showPlaceHoldButton = false;
57 // If set, all holds are fetched on grid load and sorting/paging all
58 // happens in the client. If false, sorting and paging occur on
60 @Input() enablePreFetch: boolean;
62 // How to sort when no sort parameters have been applied
63 // via grid controls. This uses the eg-grid sort format:
64 // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
65 @Input() defaultSort: any[];
67 // To pass through to the underlying eg-grid
68 @Input() showFields: string;
70 // Display bib record summary along the top of the detail page.
71 @Input() showRecordSummary = false;
73 mode: 'list' | 'detail' | 'manage' = 'list';
78 gridDataSource: GridDataSource;
81 transferTarget: number;
83 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
84 @ViewChild('progressDialog', { static: true })
85 private progressDialog: ProgressDialogComponent;
86 @ViewChild('transferDialog', { static: true })
87 private transferDialog: HoldTransferDialogComponent;
88 @ViewChild('markDamagedDialog', { static: true })
89 private markDamagedDialog: MarkDamagedDialogComponent;
90 @ViewChild('markMissingDialog', { static: true })
91 private markMissingDialog: MarkMissingDialogComponent;
92 @ViewChild('markDiscardDialog')
93 private markDiscardDialog: MarkDiscardDialogComponent;
94 @ViewChild('retargetDialog', { static: true })
95 private retargetDialog: HoldRetargetDialogComponent;
96 @ViewChild('cancelDialog', { static: true })
97 private cancelDialog: HoldCancelDialogComponent;
98 @ViewChild('manageDialog', { static: true })
99 private manageDialog: HoldManageDialogComponent;
103 @Input() set recordId(id: number) {
105 if (this.initDone) { // reload on update
106 this.holdsGrid.reload();
110 get recordId(): number {
111 return this._recordId;
115 @Input() set patronId(id: number) {
118 this.holdsGrid.reload();
121 get patronId(): number {
122 return this._patronId;
125 // If true, show recently canceled holds only.
126 @Input() showRecentlyCanceled = false;
128 // Include holds fulfilled on or after hte provided date.
129 // If no value is passed, fulfilled holds are not displayed.
130 _showFulfilledSince: Date;
131 @Input() set showFulfilledSince(show: Date) {
132 this._showFulfilledSince = show;
133 if (this.initDone) { // reload on update
134 this.holdsGrid.reload();
137 get showFulfilledSince(): Date {
138 return this._showFulfilledSince;
142 cellTextGenerator: GridCellTextGenerator;
144 // Include holds marked Hopeless on or after this date.
145 _showHopelessAfter: Date;
146 @Input() set showHopelessAfter(show: Date) {
147 this._showHopelessAfter = show;
148 if (this.initDone) { // reload on update
149 this.holdsGrid.reload();
153 // Include holds marked Hopeless on or before this date.
154 _showHopelessBefore: Date;
155 @Input() set showHopelessBefore(show: Date) {
156 this._showHopelessBefore = show;
157 if (this.initDone) { // reload on update
158 this.holdsGrid.reload();
162 // Notify the caller the place hold button was clicked.
163 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
166 private ngLocation: Location,
167 private net: NetService,
168 private org: OrgService,
169 private store: ServerStoreService,
170 private auth: AuthService,
171 private printer: PrintService,
172 private holdings: HoldingsService
174 this.gridDataSource = new GridDataSource();
175 this.enablePreFetch = null;
179 this.initDone = true;
180 this.pickupLib = this.org.get(this.initialPickupLib);
182 if (this.preFetchSetting) {
183 this.store.getItem(this.preFetchSetting).then(
184 applied => this.enablePreFetch = Boolean(applied)
187 this.enablePreFetch = false;
190 if (!this.defaultSort) {
191 if (this.pullListOrg) {
194 {name: 'copy_location_order_position', dir: 'asc'},
195 {name: 'acpl_name', dir: 'asc'},
196 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
197 {name: 'cn_label_sortkey', dir: 'asc'},
198 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
202 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
206 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
208 if (!this.hidePickupLibFilter && !this.plCompLoaded) {
209 // When the pickup lib selector is active, avoid any
210 // data fetches until it has settled on a default value.
211 // Once the final value is applied, its onchange will
212 // fire and we'll be back here with plCompLoaded=true.
216 sort = sort.length > 0 ? sort : this.defaultSort;
217 return this.fetchHolds(pager, sort);
220 // Text-ify function for cells that use display templates.
221 this.cellTextGenerator = {
222 title: row => row.title,
223 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
224 current_item: row => row.current_copy ? row.cp_barcode : '',
225 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
226 ucard_barcode: row => row.ucard_barcode
230 // Returns true after all data/settings/etc required to render the
231 // grid have been fetched.
232 initComplete(): boolean {
233 return this.enablePreFetch !== null;
236 pickupLibChanged(org: IdlObject) {
237 this.pickupLib = org;
238 this.holdsGrid.reload();
241 pullListOrgChanged(org: IdlObject) {
242 this.pullListOrg = org.id();
243 this.holdsGrid.reload();
246 preFetchHolds(apply: boolean) {
247 this.enablePreFetch = apply;
250 setTimeout(() => this.holdsGrid.reload());
253 if (this.preFetchSetting) {
255 this.store.setItem(this.preFetchSetting, apply);
259 applyFilters(): any {
261 const filters: any = {};
263 if (this.pullListOrg) {
264 filters.cancel_time = null;
265 filters.capture_time = null;
266 filters.frozen = 'f';
268 // cp.* fields are set for copy-level holds even if they
269 // have no current_copy. Make sure current_copy is set.
270 filters.current_copy = {'is not': null};
272 // There are aliases for these (cp_status, cp_circ_lib),
273 // but the API complains when I use them.
274 filters['cp.status'] = [0, 7];
275 filters['cp.circ_lib'] = this.pullListOrg;
280 if (this._showFulfilledSince) {
281 filters.fulfillment_time = this._showFulfilledSince.toISOString();
283 filters.fulfillment_time = null;
286 if (this._showCanceledSince) {
287 filters.cancel_time = this._showCanceledSince.toISOString();
289 filters.cancel_time = null;
293 filters['hopeless_holds'] = {
294 'start_date' : this._showHopelessAfter
296 // FIXME -- consistency desired, string or object
297 typeof this._showHopelessAfter === 'object'
298 ? this._showHopelessAfter.toISOString()
299 : this._showHopelessAfter
301 : '1970-01-01T00:00:00.000Z',
302 'end_date' : this._showHopelessBefore
304 // FIXME -- consistency desired, string or object
305 typeof this._showHopelessBefore === 'object'
306 ? this._showHopelessBefore.toISOString()
307 : this._showHopelessBefore
309 : (new Date()).toISOString()
313 if (this.pickupLib) {
315 this.org.descendants(this.pickupLib, true);
319 filters.record_id = this.recordId;
323 filters.usr_id = this.patronId;
329 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
331 // We need at least one filter.
332 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
336 const filters = this.applyFilters();
338 const orderBy: any = [];
339 if (sort.length > 0) {
340 sort.forEach(obj => {
341 const subObj: any = {};
342 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
343 orderBy.push(subObj);
347 const limit = this.enablePreFetch ? null : pager.limit;
348 const offset = this.enablePreFetch ? 0 : pager.offset;
349 const options: any = {};
350 if (this.showRecentlyCanceled) {
351 options.recently_canceled = true;
353 filters.cancel_time = null;
356 let observer: Observer<any>;
357 const observable = new Observable(obs => observer = obs);
359 this.progressDialog.open();
360 this.progressDialog.update({value: 0, max: 1});
365 'open-ils.circ.hold.wide_hash.stream',
366 this.auth.token(), filters, orderBy, limit, offset, options
370 if (first) { // First response is the hold count.
371 this.holdsCount = Number(holdData);
374 } else { // Subsequent responses are hold data blobs
376 this.progressDialog.update(
377 {value: ++loadCount, max: this.holdsCount});
379 observer.next(holdData);
383 this.progressDialog.close();
387 this.progressDialog.close();
395 metaRecordHoldsSelected(rows: IdlObject[]) {
397 rows.forEach( row => {
398 if (row.hold_type === 'M') {
405 nonTitleHoldsSelected(rows: IdlObject[]) {
407 rows.forEach( row => {
408 if (row.hold_type !== 'T') {
415 showDetails(rows: any[]) {
416 this.showDetail(rows[0]);
419 showHoldsForTitle(rows: any[]) {
420 if (rows.length === 0) { return; }
422 const url = this.ngLocation.prepareExternalUrl(
423 `/staff/catalog/record/${rows[0].record_id}/holds`);
425 window.open(url, '_blank');
428 showDetail(row: any) {
430 this.mode = 'detail';
431 this.detailHold = row;
435 showManager(rows: any[]) {
437 this.mode = 'manage';
438 this.editHolds = rows.map(r => r.id);
442 handleModify(rowsModified: boolean) {
446 // give the grid a chance to render then ask it to reload
447 setTimeout(() => this.holdsGrid.reload());
453 showRecentCircs(rows: any[]) {
454 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
455 copyIds.forEach( copyId => {
457 '/eg/staff/cat/item/' + copyId + '/circ_list';
458 window.open(url, '_blank');
462 showPatron(rows: any[]) {
463 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
464 usrIds.forEach( usrId => {
466 '/eg/staff/circ/patron/' + usrId + '/checkout';
467 window.open(url, '_blank');
471 showOrder(rows: any[]) {
472 // Doesn't work in Typescript currently without compiler option:
473 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
474 const bibIds = Array.from(
475 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
476 bibIds.forEach( bibId => {
478 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
479 window.open(url, '_blank');
483 addVolume(rows: any[]) {
484 const bibIds = Array.from(
485 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
486 bibIds.forEach( bibId => {
487 this.holdings.spawnAddHoldingsUi(bibId);
491 showTitle(rows: any[]) {
492 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
493 bibIds.forEach( bibId => {
494 // const url = '/eg/staff/cat/catalog/record/' + bibId;
495 const url = '/eg2/staff/catalog/record/' + bibId;
496 window.open(url, '_blank');
500 showManageDialog(rows: any[]) {
501 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
502 if (holdIds.length > 0) {
503 this.manageDialog.holdIds = holdIds;
504 this.manageDialog.open({size: 'lg'}).subscribe(
507 this.holdsGrid.reload();
514 showTransferDialog(rows: any[]) {
515 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
516 if (holdIds.length > 0) {
517 this.transferDialog.holdIds = holdIds;
518 this.transferDialog.open({}).subscribe(
521 this.holdsGrid.reload();
528 async showMarkDamagedDialog(rows: any[]) {
529 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
530 if (copyIds.length === 0) { return; }
532 let rowsModified = false;
534 const markNext = async(ids: number[]) => {
535 if (ids.length === 0) {
536 return Promise.resolve();
539 this.markDamagedDialog.copyId = ids.pop();
540 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
542 if (ok) { rowsModified = true; }
543 return markNext(ids);
545 dismiss => markNext(ids)
549 await markNext(copyIds);
551 this.holdsGrid.reload();
555 showMarkMissingDialog(rows: any[]) {
556 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
557 if (copyIds.length > 0) {
558 this.markMissingDialog.copyIds = copyIds;
559 this.markMissingDialog.open({}).subscribe(
562 this.holdsGrid.reload();
569 showMarkDiscardDialog(rows: any[]) {
570 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
571 if (copyIds.length > 0) {
572 this.markDiscardDialog.copyIds = copyIds;
573 this.markDiscardDialog.open({}).subscribe(
576 this.holdsGrid.reload();
584 showRetargetDialog(rows: any[]) {
585 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
586 if (holdIds.length > 0) {
587 this.retargetDialog.holdIds = holdIds;
588 this.retargetDialog.open({}).subscribe(
591 this.holdsGrid.reload();
598 showCancelDialog(rows: any[]) {
599 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
600 if (holdIds.length > 0) {
601 this.cancelDialog.holdIds = holdIds;
602 this.cancelDialog.open({}).subscribe(
605 this.holdsGrid.reload();
613 // Request a page with no limit to get all of the wide holds for
614 // printing. Call requestPage() directly instead of grid.reload()
615 // since we may already have the data.
617 const pager = new Pager();
621 if (this.gridDataSource.sort.length === 0) {
622 this.gridDataSource.sort = this.defaultSort;
625 this.gridDataSource.requestPage(pager).then(() => {
626 if (this.gridDataSource.data.length > 0) {
628 templateName: this.printTemplate || 'holds_for_bib',
629 contextData: this.gridDataSource.data,
630 printContext: 'default'
636 isCopyHold(holdData: any): boolean {
637 return holdData.hold_type.match(/C|R|F/) !== null;