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;
97 @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
98 @ViewChild('progressDialog', { static: true })
99 private progressDialog: ProgressDialogComponent;
100 @ViewChild('transferDialog', { static: true })
101 private transferDialog: HoldTransferDialogComponent;
102 @ViewChild('markDamagedDialog', { static: true })
103 private markDamagedDialog: MarkDamagedDialogComponent;
104 @ViewChild('markMissingDialog', { static: true })
105 private markMissingDialog: MarkMissingDialogComponent;
106 @ViewChild('markDiscardDialog')
107 private markDiscardDialog: MarkDiscardDialogComponent;
108 @ViewChild('retargetDialog', { static: true })
109 private retargetDialog: HoldRetargetDialogComponent;
110 @ViewChild('cancelDialog', { static: true })
111 private cancelDialog: HoldCancelDialogComponent;
112 @ViewChild('manageDialog', { static: true })
113 private manageDialog: HoldManageDialogComponent;
114 @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
118 @Input() set recordId(id: number) {
120 if (this.initDone) { // reload on update
121 this.holdsGrid.reload();
125 get recordId(): number {
126 return this._recordId;
130 @Input() set patronId(id: number) {
133 this.holdsGrid.reload();
136 get patronId(): number {
137 return this._patronId;
140 // If true, show recently canceled holds only.
141 @Input() showRecentlyCanceled = false;
143 // Include holds fulfilled on or after hte provided date.
144 // If no value is passed, fulfilled holds are not displayed.
145 _showFulfilledSince: Date;
146 @Input() set showFulfilledSince(show: Date) {
147 this._showFulfilledSince = show;
148 if (this.initDone) { // reload on update
149 this.holdsGrid.reload();
152 get showFulfilledSince(): Date {
153 return this._showFulfilledSince;
157 cellTextGenerator: GridCellTextGenerator;
159 // Include holds marked Hopeless on or after this date.
160 _showHopelessAfter: Date;
161 @Input() set showHopelessAfter(show: Date) {
162 this._showHopelessAfter = show;
163 if (this.initDone) { // reload on update
164 this.holdsGrid.reload();
168 // Include holds marked Hopeless on or before this date.
169 _showHopelessBefore: Date;
170 @Input() set showHopelessBefore(show: Date) {
171 this._showHopelessBefore = show;
172 if (this.initDone) { // reload on update
173 this.holdsGrid.reload();
177 // Notify the caller the place hold button was clicked.
178 @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
181 private ngLocation: Location,
182 private net: NetService,
183 private org: OrgService,
184 private store: ServerStoreService,
185 private auth: AuthService,
186 private printer: PrintService,
187 private holdings: HoldingsService
189 this.gridDataSource = new GridDataSource();
190 this.enablePreFetch = null;
194 this.initDone = true;
195 this.pickupLib = this.org.get(this.initialPickupLib);
197 if (this.preFetchSetting) {
198 this.store.getItem(this.preFetchSetting).then(
199 applied => this.enablePreFetch = Boolean(applied)
202 this.enablePreFetch = false;
205 if (!this.defaultSort) {
206 if (this.pullListOrg) {
209 {name: 'copy_location_order_position', dir: 'asc'},
210 {name: 'acpl_name', dir: 'asc'},
211 {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
212 {name: 'cn_label_sortkey', dir: 'asc'},
213 {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
217 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
221 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
223 if (!this.hidePickupLibFilter && !this.plCompLoaded) {
224 // When the pickup lib selector is active, avoid any
225 // data fetches until it has settled on a default value.
226 // Once the final value is applied, its onchange will
227 // fire and we'll be back here with plCompLoaded=true.
231 sort = sort.length > 0 ? sort : this.defaultSort;
232 return this.fetchHolds(pager, sort);
235 // Text-ify function for cells that use display templates.
236 this.cellTextGenerator = {
237 title: row => row.title,
238 cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
239 current_item: row => row.current_copy ? row.cp_barcode : '',
240 requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
241 ucard_barcode: row => row.ucard_barcode,
242 hold_status: row => row.hold_status // TODO labels
246 // Returns true after all data/settings/etc required to render the
247 // grid have been fetched.
248 initComplete(): boolean {
249 return this.enablePreFetch !== null;
252 pickupLibChanged(org: IdlObject) {
253 this.pickupLib = org;
254 this.holdsGrid.reload();
257 pullListOrgChanged(org: IdlObject) {
258 this.pullListOrg = org.id();
259 this.holdsGrid.reload();
262 preFetchHolds(apply: boolean) {
263 this.enablePreFetch = apply;
266 setTimeout(() => this.holdsGrid.reload());
269 if (this.preFetchSetting) {
271 this.store.setItem(this.preFetchSetting, apply);
275 applyFilters(): any {
277 const filters: any = {};
279 if (this.pullListOrg) {
280 filters.cancel_time = null;
281 filters.capture_time = null;
282 filters.frozen = 'f';
284 // cp.* fields are set for copy-level holds even if they
285 // have no current_copy. Make sure current_copy is set.
286 filters.current_copy = {'is not': null};
288 // There are aliases for these (cp_status, cp_circ_lib),
289 // but the API complains when I use them.
290 filters['cp.status'] = [0, 7];
291 filters['cp.circ_lib'] = this.pullListOrg;
296 if (this._showFulfilledSince) {
297 filters.fulfillment_time = this._showFulfilledSince.toISOString();
299 filters.fulfillment_time = null;
304 filters['hopeless_holds'] = {
305 'start_date' : this._showHopelessAfter
307 // FIXME -- consistency desired, string or object
308 typeof this._showHopelessAfter === 'object'
309 ? this._showHopelessAfter.toISOString()
310 : this._showHopelessAfter
312 : '1970-01-01T00:00:00.000Z',
313 'end_date' : this._showHopelessBefore
315 // FIXME -- consistency desired, string or object
316 typeof this._showHopelessBefore === 'object'
317 ? this._showHopelessBefore.toISOString()
318 : this._showHopelessBefore
320 : (new Date()).toISOString()
324 if (this.pickupLib) {
326 this.org.descendants(this.pickupLib, true);
330 filters.record_id = this.recordId;
334 filters.usr_id = this.patronId;
340 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
342 // We need at least one filter.
343 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
347 const filters = this.applyFilters();
349 const orderBy: any = [];
350 if (sort.length > 0) {
351 sort.forEach(obj => {
352 const subObj: any = {};
353 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
354 orderBy.push(subObj);
358 const limit = this.enablePreFetch ? null : pager.limit;
359 const offset = this.enablePreFetch ? 0 : pager.offset;
360 const options: any = {};
361 if (this.showRecentlyCanceled) {
362 options.recently_canceled = true;
364 filters.cancel_time = null;
367 let observer: Observer<any>;
368 const observable = new Observable(obs => observer = obs);
370 if (!this.noLoadProgress) {
371 // Note remaining dialog actions have no impact
372 this.progressDialog.open();
375 this.progressDialog.update({value: 0, max: 1});
381 'open-ils.circ.hold.wide_hash.stream',
382 this.auth.token(), filters, orderBy, limit, offset, options
386 if (first) { // First response is the hold count.
387 this.holdsCount = Number(holdData);
390 } else { // Subsequent responses are hold data blobs
392 this.progressDialog.update(
393 {value: ++loadCount, max: this.holdsCount});
395 observer.next(holdData);
399 this.progressDialog.close();
403 this.progressDialog.close();
411 metaRecordHoldsSelected(rows: IdlObject[]) {
413 rows.forEach( row => {
414 if (row.hold_type === 'M') {
421 nonTitleHoldsSelected(rows: IdlObject[]) {
423 rows.forEach( row => {
424 if (row.hold_type !== 'T') {
431 showDetails(rows: any[]) {
432 this.showDetail(rows[0]);
435 showHoldsForTitle(rows: any[]) {
436 if (rows.length === 0) { return; }
438 const url = this.ngLocation.prepareExternalUrl(
439 `/staff/catalog/record/${rows[0].record_id}/holds`);
441 window.open(url, '_blank');
444 showDetail(row: any) {
446 this.mode = 'detail';
447 this.detailHold = row;
451 showManager(rows: any[]) {
453 this.mode = 'manage';
454 this.editHolds = rows.map(r => r.id);
458 handleModify(rowsModified: boolean) {
462 // give the grid a chance to render then ask it to reload
463 setTimeout(() => this.holdsGrid.reload());
469 showRecentCircs(rows: any[]) {
470 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
471 copyIds.forEach( copyId => {
473 '/eg/staff/cat/item/' + copyId + '/circ_list';
474 window.open(url, '_blank');
478 showPatron(rows: any[]) {
479 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
480 usrIds.forEach( usrId => {
482 '/eg/staff/circ/patron/' + usrId + '/checkout';
483 window.open(url, '_blank');
487 showOrder(rows: any[]) {
488 // Doesn't work in Typescript currently without compiler option:
489 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
490 const bibIds = Array.from(
491 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
492 bibIds.forEach( bibId => {
494 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
495 window.open(url, '_blank');
499 addVolume(rows: any[]) {
500 const bibIds = Array.from(
501 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
502 bibIds.forEach( bibId => {
503 this.holdings.spawnAddHoldingsUi(bibId);
507 showTitle(rows: any[]) {
508 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
509 bibIds.forEach( bibId => {
510 // const url = '/eg/staff/cat/catalog/record/' + bibId;
511 const url = '/eg2/staff/catalog/record/' + bibId;
512 window.open(url, '_blank');
516 showManageDialog(rows: any[]) {
517 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
518 if (holdIds.length > 0) {
519 this.manageDialog.holdIds = holdIds;
520 this.manageDialog.open({size: 'lg'}).subscribe(
523 this.holdsGrid.reload();
530 showTransferDialog(rows: any[]) {
531 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
532 if (holdIds.length > 0) {
533 this.transferDialog.holdIds = holdIds;
534 this.transferDialog.open({}).subscribe(
537 this.holdsGrid.reload();
544 async showMarkDamagedDialog(rows: any[]) {
545 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
546 if (copyIds.length === 0) { return; }
548 let rowsModified = false;
550 const markNext = async(ids: number[]) => {
551 if (ids.length === 0) {
552 return Promise.resolve();
555 this.markDamagedDialog.copyId = ids.pop();
556 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
558 if (ok) { rowsModified = true; }
559 return markNext(ids);
561 dismiss => markNext(ids)
565 await markNext(copyIds);
567 this.holdsGrid.reload();
571 showMarkMissingDialog(rows: any[]) {
572 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
573 if (copyIds.length > 0) {
574 this.markMissingDialog.copyIds = copyIds;
575 this.markMissingDialog.open({}).subscribe(
578 this.holdsGrid.reload();
585 showMarkDiscardDialog(rows: any[]) {
586 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
587 if (copyIds.length > 0) {
588 this.markDiscardDialog.copyIds = copyIds;
589 this.markDiscardDialog.open({}).subscribe(
592 this.holdsGrid.reload();
600 showRetargetDialog(rows: any[]) {
601 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
602 if (holdIds.length > 0) {
603 this.retargetDialog.holdIds = holdIds;
604 this.retargetDialog.open({}).subscribe(
607 this.holdsGrid.reload();
614 showCancelDialog(rows: any[]) {
615 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
616 if (holdIds.length > 0) {
617 this.cancelDialog.holdIds = holdIds;
618 this.cancelDialog.open({}).subscribe(
621 this.holdsGrid.reload();
628 showUncancelDialog(rows: any[]) {
629 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
630 if (holdIds.length === 0) { return; }
631 this.uncancelHoldCount = holdIds.length;
633 this.uncancelDialog.open().subscribe(confirmed => {
634 if (!confirmed) { return; }
635 this.progressDialog.open();
637 from(holdIds).pipe(concatMap(holdId => {
638 return this.net.request(
640 'open-ils.circ.hold.uncancel',
641 this.auth.token(), holdId
645 if (Number(resp) !== 1) {
646 console.error('Failed uncanceling hold', resp);
651 this.progressDialog.close();
652 this.holdsGrid.reload();
659 // Request a page with no limit to get all of the wide holds for
660 // printing. Call requestPage() directly instead of grid.reload()
661 // since we may already have the data.
663 const pager = new Pager();
667 if (this.gridDataSource.sort.length === 0) {
668 this.gridDataSource.sort = this.defaultSort;
671 this.gridDataSource.requestPage(pager).then(() => {
672 if (this.gridDataSource.data.length > 0) {
674 templateName: this.printTemplate || 'holds_for_bib',
675 contextData: this.gridDataSource.data,
676 printContext: 'default'
682 isCopyHold(holdData: any): boolean {
683 return holdData.hold_type.match(/C|R|F/) !== null;