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,
227 hold_status: row => row.hold_status // TODO labels
231 // Returns true after all data/settings/etc required to render the
232 // grid have been fetched.
233 initComplete(): boolean {
234 return this.enablePreFetch !== null;
237 pickupLibChanged(org: IdlObject) {
238 this.pickupLib = org;
239 this.holdsGrid.reload();
242 pullListOrgChanged(org: IdlObject) {
243 this.pullListOrg = org.id();
244 this.holdsGrid.reload();
247 preFetchHolds(apply: boolean) {
248 this.enablePreFetch = apply;
251 setTimeout(() => this.holdsGrid.reload());
254 if (this.preFetchSetting) {
256 this.store.setItem(this.preFetchSetting, apply);
260 applyFilters(): any {
262 const filters: any = {};
264 if (this.pullListOrg) {
265 filters.cancel_time = null;
266 filters.capture_time = null;
267 filters.frozen = 'f';
269 // cp.* fields are set for copy-level holds even if they
270 // have no current_copy. Make sure current_copy is set.
271 filters.current_copy = {'is not': null};
273 // There are aliases for these (cp_status, cp_circ_lib),
274 // but the API complains when I use them.
275 filters['cp.status'] = [0, 7];
276 filters['cp.circ_lib'] = this.pullListOrg;
281 if (this._showFulfilledSince) {
282 filters.fulfillment_time = this._showFulfilledSince.toISOString();
284 filters.fulfillment_time = null;
287 if (this._showCanceledSince) {
288 filters.cancel_time = this._showCanceledSince.toISOString();
290 filters.cancel_time = null;
294 filters['hopeless_holds'] = {
295 'start_date' : this._showHopelessAfter
297 // FIXME -- consistency desired, string or object
298 typeof this._showHopelessAfter === 'object'
299 ? this._showHopelessAfter.toISOString()
300 : this._showHopelessAfter
302 : '1970-01-01T00:00:00.000Z',
303 'end_date' : this._showHopelessBefore
305 // FIXME -- consistency desired, string or object
306 typeof this._showHopelessBefore === 'object'
307 ? this._showHopelessBefore.toISOString()
308 : this._showHopelessBefore
310 : (new Date()).toISOString()
314 if (this.pickupLib) {
316 this.org.descendants(this.pickupLib, true);
320 filters.record_id = this.recordId;
324 filters.usr_id = this.patronId;
330 fetchHolds(pager: Pager, sort: any[]): Observable<any> {
332 // We need at least one filter.
333 if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
337 const filters = this.applyFilters();
339 const orderBy: any = [];
340 if (sort.length > 0) {
341 sort.forEach(obj => {
342 const subObj: any = {};
343 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
344 orderBy.push(subObj);
348 const limit = this.enablePreFetch ? null : pager.limit;
349 const offset = this.enablePreFetch ? 0 : pager.offset;
350 const options: any = {};
351 if (this.showRecentlyCanceled) {
352 options.recently_canceled = true;
354 filters.cancel_time = null;
357 let observer: Observer<any>;
358 const observable = new Observable(obs => observer = obs);
360 this.progressDialog.open();
361 this.progressDialog.update({value: 0, max: 1});
366 'open-ils.circ.hold.wide_hash.stream',
367 this.auth.token(), filters, orderBy, limit, offset, options
371 if (first) { // First response is the hold count.
372 this.holdsCount = Number(holdData);
375 } else { // Subsequent responses are hold data blobs
377 this.progressDialog.update(
378 {value: ++loadCount, max: this.holdsCount});
380 observer.next(holdData);
384 this.progressDialog.close();
388 this.progressDialog.close();
396 metaRecordHoldsSelected(rows: IdlObject[]) {
398 rows.forEach( row => {
399 if (row.hold_type === 'M') {
406 nonTitleHoldsSelected(rows: IdlObject[]) {
408 rows.forEach( row => {
409 if (row.hold_type !== 'T') {
416 showDetails(rows: any[]) {
417 this.showDetail(rows[0]);
420 showHoldsForTitle(rows: any[]) {
421 if (rows.length === 0) { return; }
423 const url = this.ngLocation.prepareExternalUrl(
424 `/staff/catalog/record/${rows[0].record_id}/holds`);
426 window.open(url, '_blank');
429 showDetail(row: any) {
431 this.mode = 'detail';
432 this.detailHold = row;
436 showManager(rows: any[]) {
438 this.mode = 'manage';
439 this.editHolds = rows.map(r => r.id);
443 handleModify(rowsModified: boolean) {
447 // give the grid a chance to render then ask it to reload
448 setTimeout(() => this.holdsGrid.reload());
454 showRecentCircs(rows: any[]) {
455 const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
456 copyIds.forEach( copyId => {
458 '/eg/staff/cat/item/' + copyId + '/circ_list';
459 window.open(url, '_blank');
463 showPatron(rows: any[]) {
464 const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
465 usrIds.forEach( usrId => {
467 '/eg/staff/circ/patron/' + usrId + '/checkout';
468 window.open(url, '_blank');
472 showOrder(rows: any[]) {
473 // Doesn't work in Typescript currently without compiler option:
474 // const bibIds = [...new Set( rows.map(r => r.record_id) )];
475 const bibIds = Array.from(
476 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
477 bibIds.forEach( bibId => {
479 '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
480 window.open(url, '_blank');
484 addVolume(rows: any[]) {
485 const bibIds = Array.from(
486 new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
487 bibIds.forEach( bibId => {
488 this.holdings.spawnAddHoldingsUi(bibId);
492 showTitle(rows: any[]) {
493 const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
494 bibIds.forEach( bibId => {
495 // const url = '/eg/staff/cat/catalog/record/' + bibId;
496 const url = '/eg2/staff/catalog/record/' + bibId;
497 window.open(url, '_blank');
501 showManageDialog(rows: any[]) {
502 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
503 if (holdIds.length > 0) {
504 this.manageDialog.holdIds = holdIds;
505 this.manageDialog.open({size: 'lg'}).subscribe(
508 this.holdsGrid.reload();
515 showTransferDialog(rows: any[]) {
516 const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
517 if (holdIds.length > 0) {
518 this.transferDialog.holdIds = holdIds;
519 this.transferDialog.open({}).subscribe(
522 this.holdsGrid.reload();
529 async showMarkDamagedDialog(rows: any[]) {
530 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
531 if (copyIds.length === 0) { return; }
533 let rowsModified = false;
535 const markNext = async(ids: number[]) => {
536 if (ids.length === 0) {
537 return Promise.resolve();
540 this.markDamagedDialog.copyId = ids.pop();
541 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
543 if (ok) { rowsModified = true; }
544 return markNext(ids);
546 dismiss => markNext(ids)
550 await markNext(copyIds);
552 this.holdsGrid.reload();
556 showMarkMissingDialog(rows: any[]) {
557 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
558 if (copyIds.length > 0) {
559 this.markMissingDialog.copyIds = copyIds;
560 this.markMissingDialog.open({}).subscribe(
563 this.holdsGrid.reload();
570 showMarkDiscardDialog(rows: any[]) {
571 const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
572 if (copyIds.length > 0) {
573 this.markDiscardDialog.copyIds = copyIds;
574 this.markDiscardDialog.open({}).subscribe(
577 this.holdsGrid.reload();
585 showRetargetDialog(rows: any[]) {
586 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
587 if (holdIds.length > 0) {
588 this.retargetDialog.holdIds = holdIds;
589 this.retargetDialog.open({}).subscribe(
592 this.holdsGrid.reload();
599 showCancelDialog(rows: any[]) {
600 const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
601 if (holdIds.length > 0) {
602 this.cancelDialog.holdIds = holdIds;
603 this.cancelDialog.open({}).subscribe(
606 this.holdsGrid.reload();
614 // Request a page with no limit to get all of the wide holds for
615 // printing. Call requestPage() directly instead of grid.reload()
616 // since we may already have the data.
618 const pager = new Pager();
622 if (this.gridDataSource.sort.length === 0) {
623 this.gridDataSource.sort = this.defaultSort;
626 this.gridDataSource.requestPage(pager).then(() => {
627 if (this.gridDataSource.data.length > 0) {
629 templateName: this.printTemplate || 'holds_for_bib',
630 contextData: this.gridDataSource.data,
631 printContext: 'default'
637 isCopyHold(holdData: any): boolean {
638 return holdData.hold_type.match(/C|R|F/) !== null;