]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1904036 Option to hide Holds grid popup dialog
[Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / share / holds / grid.component.ts
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';
26
27 /** Holds grid with access to detail page and other actions */
28
29 @Component({
30   selector: 'eg-holds-grid',
31   templateUrl: 'grid.component.html'
32 })
33 export class HoldsGridComponent implements OnInit {
34
35     // If either are set/true, the pickup lib selector will display
36     @Input() initialPickupLib: number | IdlObject;
37     @Input() hidePickupLibFilter: boolean;
38
39     // Setting a value here puts us into "pull list" mode.
40     @Input() pullListOrg: number;
41
42     // If true, only retrieve holds with a Hopeless Date
43     // and enable related Actions
44     @Input() hopeless: boolean;
45
46     // Grid persist key
47     @Input() persistKey: string;
48
49     @Input() preFetchSetting: string;
50
51     @Input() printTemplate: string;
52
53     // Adds a Place Hold grid toolbar button that emits
54     // placeHoldRequested on click.
55     @Input() showPlaceHoldButton = false;
56
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
59     // the server.
60     @Input() enablePreFetch: boolean;
61
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[];
66
67     // To pass through to the underlying eg-grid
68     @Input() showFields: string;
69
70     // Display bib record summary along the top of the detail page.
71     @Input() showRecordSummary = false;
72
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;
76
77     mode: 'list' | 'detail' | 'manage' = 'list';
78     initDone = false;
79     holdsCount: number;
80     pickupLib: IdlObject;
81     plCompLoaded = false;
82     gridDataSource: GridDataSource;
83     detailHold: any;
84     editHolds: number[];
85     transferTarget: number;
86
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;
104
105     // Bib record ID.
106     _recordId: number;
107     @Input() set recordId(id: number) {
108         this._recordId = id;
109         if (this.initDone) { // reload on update
110             this.holdsGrid.reload();
111         }
112     }
113
114     get recordId(): number {
115         return this._recordId;
116     }
117
118     _patronId: number;
119     @Input() set patronId(id: number) {
120         this._patronId = id;
121         if (this.initDone) {
122             this.holdsGrid.reload();
123         }
124     }
125     get patronId(): number {
126         return this._patronId;
127     }
128
129     // If true, show recently canceled holds only.
130     @Input() showRecentlyCanceled = false;
131
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();
139         }
140     }
141     get showFulfilledSince(): Date {
142         return this._showFulfilledSince;
143     }
144
145
146     cellTextGenerator: GridCellTextGenerator;
147
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();
154         }
155     }
156
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();
163         }
164     }
165
166     // Notify the caller the place hold button was clicked.
167     @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
168
169     constructor(
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
177     ) {
178         this.gridDataSource = new GridDataSource();
179         this.enablePreFetch = null;
180     }
181
182     ngOnInit() {
183         this.initDone = true;
184         this.pickupLib = this.org.get(this.initialPickupLib);
185
186         if (this.preFetchSetting) {
187             this.store.getItem(this.preFetchSetting).then(
188                 applied => this.enablePreFetch = Boolean(applied)
189             );
190         } else {
191             this.enablePreFetch = false;
192         }
193
194         if (!this.defaultSort) {
195             if (this.pullListOrg) {
196
197                 this.defaultSort = [
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"
203                 ];
204
205             } else {
206                 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
207             }
208         }
209
210         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
211
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.
217                 return of([]);
218             }
219
220             sort = sort.length > 0 ? sort : this.defaultSort;
221             return this.fetchHolds(pager, sort);
222         };
223
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
232         };
233     }
234
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;
239     }
240
241     pickupLibChanged(org: IdlObject) {
242         this.pickupLib = org;
243         this.holdsGrid.reload();
244     }
245
246     pullListOrgChanged(org: IdlObject) {
247         this.pullListOrg = org.id();
248         this.holdsGrid.reload();
249     }
250
251     preFetchHolds(apply: boolean) {
252         this.enablePreFetch = apply;
253
254         if (apply) {
255             setTimeout(() => this.holdsGrid.reload());
256         }
257
258         if (this.preFetchSetting) {
259             // fire and forget
260             this.store.setItem(this.preFetchSetting, apply);
261         }
262     }
263
264     applyFilters(): any {
265
266         const filters: any = {};
267
268         if (this.pullListOrg) {
269             filters.cancel_time = null;
270             filters.capture_time = null;
271             filters.frozen = 'f';
272
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};
276
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;
281
282             return filters;
283         }
284
285         if (this._showFulfilledSince) {
286             filters.fulfillment_time = this._showFulfilledSince.toISOString();
287         } else {
288             filters.fulfillment_time = null;
289         }
290
291         if (this._showCanceledSince) {
292             filters.cancel_time = this._showCanceledSince.toISOString();
293         } else {
294             filters.cancel_time = null;
295         }
296
297         if (this.hopeless) {
298           filters['hopeless_holds'] = {
299             'start_date' : this._showHopelessAfter
300               ? (
301                   // FIXME -- consistency desired, string or object
302                   typeof this._showHopelessAfter === 'object'
303                   ? this._showHopelessAfter.toISOString()
304                   : this._showHopelessAfter
305                 )
306               : '1970-01-01T00:00:00.000Z',
307             'end_date' : this._showHopelessBefore
308               ? (
309                   // FIXME -- consistency desired, string or object
310                   typeof this._showHopelessBefore === 'object'
311                   ? this._showHopelessBefore.toISOString()
312                   : this._showHopelessBefore
313                 )
314               : (new Date()).toISOString()
315           };
316         }
317
318         if (this.pickupLib) {
319             filters.pickup_lib =
320                 this.org.descendants(this.pickupLib, true);
321         }
322
323         if (this.recordId) {
324             filters.record_id = this.recordId;
325         }
326
327         if (this.patronId) {
328             filters.usr_id = this.patronId;
329         }
330
331         return filters;
332     }
333
334     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
335
336         // We need at least one filter.
337         if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
338             return of([]);
339         }
340
341         const filters = this.applyFilters();
342
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);
349             });
350         }
351
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;
357         } else {
358             filters.cancel_time = null;
359         }
360
361         let observer: Observer<any>;
362         const observable = new Observable(obs => observer = obs);
363
364         if (!this.noLoadProgress) {
365             // Note remaining dialog actions have no impact
366             this.progressDialog.open();
367         }
368
369         this.progressDialog.update({value: 0, max: 1});
370
371         let first = true;
372         let loadCount = 0;
373         this.net.request(
374             'open-ils.circ',
375             'open-ils.circ.hold.wide_hash.stream',
376             this.auth.token(), filters, orderBy, limit, offset, options
377         ).subscribe(
378             holdData => {
379
380                 if (first) { // First response is the hold count.
381                     this.holdsCount = Number(holdData);
382                     first = false;
383
384                 } else { // Subsequent responses are hold data blobs
385
386                     this.progressDialog.update(
387                         {value: ++loadCount, max: this.holdsCount});
388
389                     observer.next(holdData);
390                 }
391             },
392             err => {
393                 this.progressDialog.close();
394                 observer.error(err);
395             },
396             ()  => {
397                 this.progressDialog.close();
398                 observer.complete();
399             }
400         );
401
402         return observable;
403     }
404
405     metaRecordHoldsSelected(rows: IdlObject[]) {
406         let found = false;
407         rows.forEach( row => {
408            if (row.hold_type === 'M') {
409              found = true;
410            }
411         });
412         return found;
413     }
414
415     nonTitleHoldsSelected(rows: IdlObject[]) {
416         let found = false;
417         rows.forEach( row => {
418            if (row.hold_type !== 'T') {
419              found = true;
420            }
421         });
422         return found;
423     }
424
425     showDetails(rows: any[]) {
426         this.showDetail(rows[0]);
427     }
428
429     showHoldsForTitle(rows: any[]) {
430         if (rows.length === 0) { return; }
431
432         const url = this.ngLocation.prepareExternalUrl(
433             `/staff/catalog/record/${rows[0].record_id}/holds`);
434
435         window.open(url, '_blank');
436     }
437
438     showDetail(row: any) {
439         if (row) {
440             this.mode = 'detail';
441             this.detailHold = row;
442         }
443     }
444
445     showManager(rows: any[]) {
446         if (rows.length) {
447             this.mode = 'manage';
448             this.editHolds = rows.map(r => r.id);
449         }
450     }
451
452     handleModify(rowsModified: boolean) {
453         this.mode = 'list';
454
455         if (rowsModified) {
456             // give the grid a chance to render then ask it to reload
457             setTimeout(() => this.holdsGrid.reload());
458         }
459     }
460
461
462
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 => {
466             const url =
467                 '/eg/staff/cat/item/' + copyId + '/circ_list';
468             window.open(url, '_blank');
469         });
470     }
471
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 => {
475             const url =
476                 '/eg/staff/circ/patron/' + usrId + '/checkout';
477             window.open(url, '_blank');
478         });
479     }
480
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 => {
487           const url =
488               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
489           window.open(url, '_blank');
490         });
491     }
492
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);
498         });
499     }
500
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');
507         });
508     }
509
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(
515                 rowsModified => {
516                     if (rowsModified) {
517                         this.holdsGrid.reload();
518                     }
519                 }
520             );
521         }
522     }
523
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(
529                 rowsModified => {
530                     if (rowsModified) {
531                         this.holdsGrid.reload();
532                     }
533                 }
534             );
535         }
536     }
537
538     async showMarkDamagedDialog(rows: any[]) {
539         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
540         if (copyIds.length === 0) { return; }
541
542         let rowsModified = false;
543
544         const markNext = async(ids: number[]) => {
545             if (ids.length === 0) {
546                 return Promise.resolve();
547             }
548
549             this.markDamagedDialog.copyId = ids.pop();
550             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
551                 ok => {
552                     if (ok) { rowsModified = true; }
553                     return markNext(ids);
554                 },
555                 dismiss => markNext(ids)
556             );
557         };
558
559         await markNext(copyIds);
560         if (rowsModified) {
561             this.holdsGrid.reload();
562         }
563     }
564
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(
570                 rowsModified => {
571                     if (rowsModified) {
572                         this.holdsGrid.reload();
573                     }
574                 }
575             );
576         }
577     }
578
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(
584                 rowsModified => {
585                     if (rowsModified) {
586                         this.holdsGrid.reload();
587                     }
588                 }
589             );
590         }
591     }
592
593
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(
599                 rowsModified => {
600                     if (rowsModified) {
601                         this.holdsGrid.reload();
602                     }
603                 }
604             );
605         }
606     }
607
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(
613                 rowsModified => {
614                     if (rowsModified) {
615                         this.holdsGrid.reload();
616                     }
617                 }
618             );
619         }
620     }
621
622     printHolds() {
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.
626
627         const pager = new Pager();
628         pager.offset = 0;
629         pager.limit = null;
630
631         if (this.gridDataSource.sort.length === 0) {
632             this.gridDataSource.sort = this.defaultSort;
633         }
634
635         this.gridDataSource.requestPage(pager).then(() => {
636             if (this.gridDataSource.data.length > 0) {
637                 this.printer.print({
638                     templateName: this.printTemplate || 'holds_for_bib',
639                     contextData: this.gridDataSource.data,
640                     printContext: 'default'
641                 });
642             }
643         });
644     }
645
646     isCopyHold(holdData: any): boolean {
647         return holdData.hold_type.match(/C|R|F/) !== null;
648     }
649 }
650
651
652
653