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 // If true, avoid popping up the progress dialog. Note the grid
74 // has it's own generic embedded 'loading' progress indicator.
75 @Input() noLoadProgress = false;
77 mode: 'list' | 'detail' | 'manage' = 'list';
82 gridDataSource: GridDataSource;
85 transferTarget: number;
87 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
88 @ViewChild('progressDialog', { static: true })
89 private progressDialog: ProgressDialogComponent;
90 @ViewChild('transferDialog', { static: true })
91 private transferDialog: HoldTransferDialogComponent;
92 @ViewChild('markDamagedDialog', { static: true })
93 private markDamagedDialog: MarkDamagedDialogComponent;
94 @ViewChild('markMissingDialog', { static: true })
95 private markMissingDialog: MarkMissingDialogComponent;
96 @ViewChild('markDiscardDialog')
97 private markDiscardDialog: MarkDiscardDialogComponent;
98 @ViewChild('retargetDialog', { static: true })
99 private retargetDialog: HoldRetargetDialogComponent;
100 @ViewChild('cancelDialog', { static: true })
101 private cancelDialog: HoldCancelDialogComponent;
102 @ViewChild('manageDialog', { static: true })
103 private manageDialog: HoldManageDialogComponent;
107 @Input() set recordId(id: number) {
109 if (this.initDone) { // reload on update
110 this.holdsGrid.reload();
114 get recordId(): number {
115 return this._recordId;
119 @Input() set patronId(id: number) {
122 this.holdsGrid.reload();
125 get patronId(): number {
126 return this._patronId;
129 // If true, show recently canceled holds only.
130 @Input() showRecentlyCanceled = false;
132 // Include holds fulfilled on or after hte provided date.
133 // If no value is passed, fulfilled holds are not displayed.
134 _showFulfilledSince: Date;
135 @Input() set showFulfilledSince(show: Date) {
136 this._showFulfilledSince = show;
137 if (this.initDone) { // reload on update
138 this.holdsGrid.reload();
141 get showFulfilledSince(): Date {
142 return this._showFulfilledSince;
146 cellTextGenerator: GridCellTextGenerator;
148 // Include holds marked Hopeless on or after this date.
149 _showHopelessAfter: Date;
150 @Input() set showHopelessAfter(show: Date) {
151 this._showHopelessAfter = show;
152 if (this.initDone) { // reload on update
153 this.holdsGrid.reload();
157 // Include holds marked Hopeless on or before this date.
158 _showHopelessBefore: Date;
159 @Input() set showHopelessBefore(show: Date) {
160 this._showHopelessBefore = show;
161 if (this.initDone) { // reload on update
162 this.holdsGrid.reload();
166 // Notify the caller the place hold button was clicked.
167 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
170 private ngLocation: Location,
171 private net: NetService,
172 private org: OrgService,
173 private store: ServerStoreService,
174 private auth: AuthService,
175 private printer: PrintService,
176 private holdings: HoldingsService
178 this.gridDataSource = new GridDataSource();
179 this.enablePreFetch = null;
183 this.initDone = true;
184 this.pickupLib = this.org.get(this.initialPickupLib);
186 if (this.preFetchSetting) {
187 this.store.getItem(this.preFetchSetting).then(
188 applied => this.enablePreFetch = Boolean(applied)
191 this.enablePreFetch = false;
194 if (!this.defaultSort) {
195 if (this.pullListOrg) {
198 {name: 'copy_location_order_position', dir: 'asc'},
199 {name: 'acpl_name', dir: 'asc'},
200 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
201 {name: 'cn_label_sortkey', dir: 'asc'},
202 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
206 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
210 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
212 if (!this.hidePickupLibFilter && !this.plCompLoaded) {
213 // When the pickup lib selector is active, avoid any
214 // data fetches until it has settled on a default value.
215 // Once the final value is applied, its onchange will
216 // fire and we'll be back here with plCompLoaded=true.
220 sort = sort.length > 0 ? sort : this.defaultSort;
221 return this.fetchHolds(pager, sort);
224 // Text-ify function for cells that use display templates.
225 this.cellTextGenerator = {
226 title: row => row.title,
227 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
228 current_item: row => row.current_copy ? row.cp_barcode : '',
229 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
230 ucard_barcode: row => row.ucard_barcode,
231 hold_status: row => row.hold_status // TODO labels
235 // Returns true after all data/settings/etc required to render the
236 // grid have been fetched.
237 initComplete(): boolean {
238 return this.enablePreFetch !== null;
241 pickupLibChanged(org: IdlObject) {
242 this.pickupLib = org;
243 this.holdsGrid.reload();
246 pullListOrgChanged(org: IdlObject) {
247 this.pullListOrg = org.id();
248 this.holdsGrid.reload();
251 preFetchHolds(apply: boolean) {
252 this.enablePreFetch = apply;
255 setTimeout(() => this.holdsGrid.reload());
258 if (this.preFetchSetting) {
260 this.store.setItem(this.preFetchSetting, apply);
264 applyFilters(): any {
266 const filters: any = {};
268 if (this.pullListOrg) {
269 filters.cancel_time = null;
270 filters.capture_time = null;
271 filters.frozen = 'f';
273 // cp.* fields are set for copy-level holds even if they
274 // have no current_copy. Make sure current_copy is set.
275 filters.current_copy = {'is not': null};
277 // There are aliases for these (cp_status, cp_circ_lib),
278 // but the API complains when I use them.
279 filters['cp.status'] = [0, 7];
280 filters['cp.circ_lib'] = this.pullListOrg;
285 if (this._showFulfilledSince) {
286 filters.fulfillment_time = this._showFulfilledSince.toISOString();
288 filters.fulfillment_time = null;
291 if (this._showCanceledSince) {
292 filters.cancel_time = this._showCanceledSince.toISOString();
294 filters.cancel_time = null;
298 filters['hopeless_holds'] = {
299 'start_date' : this._showHopelessAfter
301 // FIXME -- consistency desired, string or object
302 typeof this._showHopelessAfter === 'object'
303 ? this._showHopelessAfter.toISOString()
304 : this._showHopelessAfter
306 : '1970-01-01T00:00:00.000Z',
307 'end_date' : this._showHopelessBefore
309 // FIXME -- consistency desired, string or object
310 typeof this._showHopelessBefore === 'object'
311 ? this._showHopelessBefore.toISOString()
312 : this._showHopelessBefore
314 : (new Date()).toISOString()
318 if (this.pickupLib) {
320 this.org.descendants(this.pickupLib, true);
324 filters.record_id = this.recordId;
328 filters.usr_id = this.patronId;
334 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
336 // We need at least one filter.
337 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
341 const filters = this.applyFilters();
343 const orderBy: any = [];
344 if (sort.length > 0) {
345 sort.forEach(obj => {
346 const subObj: any = {};
347 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
348 orderBy.push(subObj);
352 const limit = this.enablePreFetch ? null : pager.limit;
353 const offset = this.enablePreFetch ? 0 : pager.offset;
354 const options: any = {};
355 if (this.showRecentlyCanceled) {
356 options.recently_canceled = true;
358 filters.cancel_time = null;
361 let observer: Observer<any>;
362 const observable = new Observable(obs => observer = obs);
364 if (!this.noLoadProgress) {
365 // Note remaining dialog actions have no impact
366 this.progressDialog.open();
369 this.progressDialog.update({value: 0, max: 1});
375 'open-ils.circ.hold.wide_hash.stream',
376 this.auth.token(), filters, orderBy, limit, offset, options
380 if (first) { // First response is the hold count.
381 this.holdsCount = Number(holdData);
384 } else { // Subsequent responses are hold data blobs
386 this.progressDialog.update(
387 {value: ++loadCount, max: this.holdsCount});
389 observer.next(holdData);
393 this.progressDialog.close();
397 this.progressDialog.close();
405 metaRecordHoldsSelected(rows: IdlObject[]) {
407 rows.forEach( row => {
408 if (row.hold_type === 'M') {
415 nonTitleHoldsSelected(rows: IdlObject[]) {
417 rows.forEach( row => {
418 if (row.hold_type !== 'T') {
425 showDetails(rows: any[]) {
426 this.showDetail(rows[0]);
429 showHoldsForTitle(rows: any[]) {
430 if (rows.length === 0) { return; }
432 const url = this.ngLocation.prepareExternalUrl(
433 `/staff/catalog/record/${rows[0].record_id}/holds`);
435 window.open(url, '_blank');
438 showDetail(row: any) {
440 this.mode = 'detail';
441 this.detailHold = row;
445 showManager(rows: any[]) {
447 this.mode = 'manage';
448 this.editHolds = rows.map(r => r.id);
452 handleModify(rowsModified: boolean) {
456 // give the grid a chance to render then ask it to reload
457 setTimeout(() => this.holdsGrid.reload());
463 showRecentCircs(rows: any[]) {
464 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
465 copyIds.forEach( copyId => {
467 '/eg/staff/cat/item/' + copyId + '/circ_list';
468 window.open(url, '_blank');
472 showPatron(rows: any[]) {
473 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
474 usrIds.forEach( usrId => {
476 '/eg/staff/circ/patron/' + usrId + '/checkout';
477 window.open(url, '_blank');
481 showOrder(rows: any[]) {
482 // Doesn't work in Typescript currently without compiler option:
483 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
484 const bibIds = Array.from(
485 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
486 bibIds.forEach( bibId => {
488 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
489 window.open(url, '_blank');
493 addVolume(rows: any[]) {
494 const bibIds = Array.from(
495 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
496 bibIds.forEach( bibId => {
497 this.holdings.spawnAddHoldingsUi(bibId);
501 showTitle(rows: any[]) {
502 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
503 bibIds.forEach( bibId => {
504 // const url = '/eg/staff/cat/catalog/record/' + bibId;
505 const url = '/eg2/staff/catalog/record/' + bibId;
506 window.open(url, '_blank');
510 showManageDialog(rows: any[]) {
511 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
512 if (holdIds.length > 0) {
513 this.manageDialog.holdIds = holdIds;
514 this.manageDialog.open({size: 'lg'}).subscribe(
517 this.holdsGrid.reload();
524 showTransferDialog(rows: any[]) {
525 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
526 if (holdIds.length > 0) {
527 this.transferDialog.holdIds = holdIds;
528 this.transferDialog.open({}).subscribe(
531 this.holdsGrid.reload();
538 async showMarkDamagedDialog(rows: any[]) {
539 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
540 if (copyIds.length === 0) { return; }
542 let rowsModified = false;
544 const markNext = async(ids: number[]) => {
545 if (ids.length === 0) {
546 return Promise.resolve();
549 this.markDamagedDialog.copyId = ids.pop();
550 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
552 if (ok) { rowsModified = true; }
553 return markNext(ids);
555 dismiss => markNext(ids)
559 await markNext(copyIds);
561 this.holdsGrid.reload();
565 showMarkMissingDialog(rows: any[]) {
566 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
567 if (copyIds.length > 0) {
568 this.markMissingDialog.copyIds = copyIds;
569 this.markMissingDialog.open({}).subscribe(
572 this.holdsGrid.reload();
579 showMarkDiscardDialog(rows: any[]) {
580 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
581 if (copyIds.length > 0) {
582 this.markDiscardDialog.copyIds = copyIds;
583 this.markDiscardDialog.open({}).subscribe(
586 this.holdsGrid.reload();
594 showRetargetDialog(rows: any[]) {
595 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
596 if (holdIds.length > 0) {
597 this.retargetDialog.holdIds = holdIds;
598 this.retargetDialog.open({}).subscribe(
601 this.holdsGrid.reload();
608 showCancelDialog(rows: any[]) {
609 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
610 if (holdIds.length > 0) {
611 this.cancelDialog.holdIds = holdIds;
612 this.cancelDialog.open({}).subscribe(
615 this.holdsGrid.reload();
623 // Request a page with no limit to get all of the wide holds for
624 // printing. Call requestPage() directly instead of grid.reload()
625 // since we may already have the data.
627 const pager = new Pager();
631 if (this.gridDataSource.sort.length === 0) {
632 this.gridDataSource.sort = this.defaultSort;
635 this.gridDataSource.requestPage(pager).then(() => {
636 if (this.gridDataSource.data.length > 0) {
638 templateName: this.printTemplate || 'holds_for_bib',
639 contextData: this.gridDataSource.data,
640 printContext: 'default'
646 isCopyHold(holdData: any): boolean {
647 return holdData.hold_type.match(/C|R|F/) !== null;