]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1968070 Pull List Copy Location Filter
[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} 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';
28
29 /** Holds grid with access to detail page and other actions */
30
31 @Component({
32   selector: 'eg-holds-grid',
33   templateUrl: 'grid.component.html'
34 })
35 export class HoldsGridComponent implements OnInit {
36
37     // Hide the "Holds Count" header
38     @Input() hideHoldsCount = false;
39
40     // If either are set/true, the pickup lib selector will display
41     @Input() initialPickupLib: number | IdlObject;
42     @Input() hidePickupLibFilter: boolean;
43
44     // Setting a value here puts us into "pull list" mode.
45     @Input() pullListOrg: number;
46
47     // If true, only retrieve holds with a Hopeless Date
48     // and enable related Actions
49     @Input() hopeless: boolean;
50
51     // Grid persist key
52     @Input() persistKey: string;
53
54     @Input() preFetchSetting: string;
55
56     @Input() printTemplate: string;
57
58     // Adds a Place Hold grid toolbar button that emits
59     // placeHoldRequested on click.
60     @Input() showPlaceHoldButton = false;
61
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
64     // the server.
65     @Input() enablePreFetch: boolean;
66
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[];
71
72     // To pass through to the underlying eg-grid
73     @Input() showFields: string;
74
75     // Display bib record summary along the top of the detail page.
76     @Input() showRecordSummary = false;
77
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;
81
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;
85
86     mode: 'list' | 'detail' | 'manage' = 'list';
87     initDone = false;
88     holdsCount: number;
89     pickupLib: IdlObject;
90     plCompLoaded = false;
91     gridDataSource: GridDataSource;
92     detailHold: any;
93     editHolds: number[];
94     transferTarget: number;
95     uncancelHoldCount: number;
96     copyLocation: number;
97
98     @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
99     @ViewChild('progressDialog', { static: true })
100         private progressDialog: ProgressDialogComponent;
101     @ViewChild('transferDialog', { static: true })
102         private transferDialog: HoldTransferDialogComponent;
103     @ViewChild('markDamagedDialog', { static: true })
104         private markDamagedDialog: MarkDamagedDialogComponent;
105     @ViewChild('markMissingDialog', { static: true })
106         private markMissingDialog: MarkMissingDialogComponent;
107     @ViewChild('markDiscardDialog')
108         private markDiscardDialog: MarkDiscardDialogComponent;
109     @ViewChild('retargetDialog', { static: true })
110         private retargetDialog: HoldRetargetDialogComponent;
111     @ViewChild('cancelDialog', { static: true })
112         private cancelDialog: HoldCancelDialogComponent;
113     @ViewChild('manageDialog', { static: true })
114         private manageDialog: HoldManageDialogComponent;
115     @ViewChild('uncancelDialog') private uncancelDialog: ConfirmDialogComponent;
116
117     // Bib record ID.
118     _recordId: number;
119     @Input() set recordId(id: number) {
120         this._recordId = id;
121         if (this.initDone) { // reload on update
122             this.holdsGrid.reload();
123         }
124     }
125
126     get recordId(): number {
127         return this._recordId;
128     }
129
130     _patronId: number;
131     @Input() set patronId(id: number) {
132         this._patronId = id;
133         if (this.initDone) {
134             this.holdsGrid.reload();
135         }
136     }
137     get patronId(): number {
138         return this._patronId;
139     }
140
141     // If true, show recently canceled holds only.
142     @Input() showRecentlyCanceled = false;
143
144     // Include holds fulfilled on or after hte provided date.
145     // If no value is passed, fulfilled holds are not displayed.
146     _showFulfilledSince: Date;
147     @Input() set showFulfilledSince(show: Date) {
148         this._showFulfilledSince = show;
149         if (this.initDone) { // reload on update
150             this.holdsGrid.reload();
151         }
152     }
153     get showFulfilledSince(): Date {
154         return this._showFulfilledSince;
155     }
156
157
158     cellTextGenerator: GridCellTextGenerator;
159
160     // Include holds marked Hopeless on or after this date.
161     _showHopelessAfter: Date;
162     @Input() set showHopelessAfter(show: Date) {
163         this._showHopelessAfter = show;
164         if (this.initDone) { // reload on update
165             this.holdsGrid.reload();
166         }
167     }
168
169     // Include holds marked Hopeless on or before this date.
170     _showHopelessBefore: Date;
171     @Input() set showHopelessBefore(show: Date) {
172         this._showHopelessBefore = show;
173         if (this.initDone) { // reload on update
174             this.holdsGrid.reload();
175         }
176     }
177
178     // Notify the caller the place hold button was clicked.
179     @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
180
181     constructor(
182         private ngLocation: Location,
183         private net: NetService,
184         private org: OrgService,
185         private store: ServerStoreService,
186         private auth: AuthService,
187         private printer: PrintService,
188         private holdings: HoldingsService
189     ) {
190         this.gridDataSource = new GridDataSource();
191         this.enablePreFetch = null;
192     }
193
194     ngOnInit() {
195         this.initDone = true;
196         this.pickupLib = this.org.get(this.initialPickupLib);
197
198         if (this.preFetchSetting) {
199             this.store.getItem(this.preFetchSetting).then(
200                 applied => this.enablePreFetch = Boolean(applied)
201             );
202         } else {
203             this.enablePreFetch = false;
204         }
205
206         if (!this.defaultSort) {
207             if (this.pullListOrg) {
208
209                 this.defaultSort = [
210                     {name: 'copy_location_order_position', dir: 'asc'},
211                     {name: 'acpl_name', dir: 'asc'},
212                     {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
213                     {name: 'cn_label_sortkey', dir: 'asc'},
214                     {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
215                 ];
216
217             } else {
218                 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
219             }
220         }
221
222         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
223
224             if (!this.hidePickupLibFilter && !this.plCompLoaded) {
225                 // When the pickup lib selector is active, avoid any
226                 // data fetches until it has settled on a default value.
227                 // Once the final value is applied, its onchange will
228                 // fire and we'll be back here with plCompLoaded=true.
229                 return of([]);
230             }
231
232             sort = sort.length > 0 ? sort : this.defaultSort;
233             return this.fetchHolds(pager, sort);
234         };
235
236         // Text-ify function for cells that use display templates.
237         this.cellTextGenerator = {
238             title: row => row.title,
239             cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
240             current_item: row => row.current_copy ? row.cp_barcode : '',
241             requested_item: row => this.isCopyHold(row) ? row.cp_barcode : '',
242             ucard_barcode: row => row.ucard_barcode,
243             hold_status: row => row.hold_status // TODO labels
244         };
245     }
246
247     // Returns true after all data/settings/etc required to render the
248     // grid have been fetched.
249     initComplete(): boolean {
250         return this.enablePreFetch !== null;
251     }
252
253     pickupLibChanged(org: IdlObject) {
254         this.pickupLib = org;
255         this.holdsGrid.reload();
256     }
257
258     pullListOrgChanged(org: IdlObject) {
259         this.pullListOrg = org.id();
260         this.holdsGrid.reload();
261     }
262
263     copyLocationChange(loc: IdlObject) {
264         this.copyLocation = loc ? loc.id() : null;
265         this.holdsGrid.reload();
266     }
267
268     preFetchHolds(apply: boolean) {
269         this.enablePreFetch = apply;
270
271         if (apply) {
272             setTimeout(() => this.holdsGrid.reload());
273         }
274
275         if (this.preFetchSetting) {
276             // fire and forget
277             this.store.setItem(this.preFetchSetting, apply);
278         }
279     }
280
281     applyFilters(): any {
282
283         const filters: any = {};
284
285         if (this.copyLocation) {
286             filters['acpl.id'] = this.copyLocation;
287         }
288
289         if (this.pullListOrg) {
290             filters.cancel_time = null;
291             filters.capture_time = null;
292             filters.frozen = 'f';
293
294             // cp.* fields are set for copy-level holds even if they
295             // have no current_copy.  Make sure current_copy is set.
296             filters.current_copy = {'is not': null};
297
298             // There are aliases for these (cp_status, cp_circ_lib),
299             // but the API complains when I use them.
300             filters['cp.status'] = {"in":{"select":{"ccs":["id"]},"from":"ccs","where":{"holdable":'t',"is_available":'t'}}};
301             filters['cp.circ_lib'] = this.pullListOrg;
302             // Avoid deleted copies AND this uses a database index on copy circ_lib where deleted is false.
303             filters['cp.deleted'] = 'f';
304
305             return filters;
306         }
307
308         if (this._showFulfilledSince) {
309             filters.fulfillment_time = this._showFulfilledSince.toISOString();
310         } else {
311             filters.fulfillment_time = null;
312         }
313
314
315         if (this.hopeless) {
316           filters['hopeless_holds'] = {
317             'start_date' : this._showHopelessAfter
318               ? (
319                   // FIXME -- consistency desired, string or object
320                   typeof this._showHopelessAfter === 'object'
321                   ? this._showHopelessAfter.toISOString()
322                   : this._showHopelessAfter
323                 )
324               : '1970-01-01T00:00:00.000Z',
325             'end_date' : this._showHopelessBefore
326               ? (
327                   // FIXME -- consistency desired, string or object
328                   typeof this._showHopelessBefore === 'object'
329                   ? this._showHopelessBefore.toISOString()
330                   : this._showHopelessBefore
331                 )
332               : (new Date()).toISOString()
333           };
334         }
335
336         if (this.pickupLib) {
337             filters.pickup_lib =
338                 this.org.descendants(this.pickupLib, true);
339         }
340
341         if (this.recordId) {
342             filters.record_id = this.recordId;
343         }
344
345         if (this.patronId) {
346             filters.usr_id = this.patronId;
347         }
348
349         return filters;
350     }
351
352     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
353
354         // We need at least one filter.
355         if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
356             return of([]);
357         }
358
359         const filters = this.applyFilters();
360
361         const orderBy: any = [];
362         if (sort.length > 0) {
363             sort.forEach(obj => {
364                 const subObj: any = {};
365                 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
366                 orderBy.push(subObj);
367             });
368         }
369
370         const limit = this.enablePreFetch ? null : pager.limit;
371         const offset = this.enablePreFetch ? 0 : pager.offset;
372         const options: any = {};
373         if (this.showRecentlyCanceled) {
374             options.recently_canceled = true;
375         } else {
376             filters.cancel_time = null;
377         }
378
379         let observer: Observer<any>;
380         const observable = new Observable(obs => observer = obs);
381
382         if (!this.noLoadProgress) {
383             // Note remaining dialog actions have no impact
384             this.progressDialog.open();
385         }
386
387         this.progressDialog.update({value: 0, max: 1});
388
389         let first = true;
390         let loadCount = 0;
391         this.net.request(
392             'open-ils.circ',
393             'open-ils.circ.hold.wide_hash.stream',
394             this.auth.token(), filters, orderBy, limit, offset, options
395         ).subscribe(
396             holdData => {
397
398                 if (first) { // First response is the hold count.
399                     this.holdsCount = Number(holdData);
400                     first = false;
401
402                 } else { // Subsequent responses are hold data blobs
403
404                     this.progressDialog.update(
405                         {value: ++loadCount, max: this.holdsCount});
406
407                     observer.next(holdData);
408                 }
409             },
410             err => {
411                 this.progressDialog.close();
412                 observer.error(err);
413             },
414             ()  => {
415                 this.progressDialog.close();
416                 observer.complete();
417             }
418         );
419
420         return observable;
421     }
422
423     metaRecordHoldsSelected(rows: IdlObject[]) {
424         let found = false;
425         rows.forEach( row => {
426            if (row.hold_type === 'M') {
427              found = true;
428            }
429         });
430         return found;
431     }
432
433     nonTitleHoldsSelected(rows: IdlObject[]) {
434         let found = false;
435         rows.forEach( row => {
436            if (row.hold_type !== 'T') {
437              found = true;
438            }
439         });
440         return found;
441     }
442
443     showDetails(rows: any[]) {
444         this.showDetail(rows[0]);
445     }
446
447     showHoldsForTitle(rows: any[]) {
448         if (rows.length === 0) { return; }
449
450         const url = this.ngLocation.prepareExternalUrl(
451             `/staff/catalog/record/${rows[0].record_id}/holds`);
452
453         window.open(url, '_blank');
454     }
455
456     showDetail(row: any) {
457         if (row) {
458             this.mode = 'detail';
459             this.detailHold = row;
460         }
461     }
462
463     showManager(rows: any[]) {
464         if (rows.length) {
465             this.mode = 'manage';
466             this.editHolds = rows.map(r => r.id);
467         }
468     }
469
470     handleModify(rowsModified: boolean) {
471         this.mode = 'list';
472
473         if (rowsModified) {
474             // give the grid a chance to render then ask it to reload
475             setTimeout(() => this.holdsGrid.reload());
476         }
477     }
478
479
480
481     showRecentCircs(rows: any[]) {
482         const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
483         copyIds.forEach( copyId => {
484             const url =
485                 '/eg/staff/cat/item/' + copyId + '/circ_list';
486             window.open(url, '_blank');
487         });
488     }
489
490     showPatron(rows: any[]) {
491         const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
492         usrIds.forEach( usrId => {
493             const url =
494                 '/eg/staff/circ/patron/' + usrId + '/checkout';
495             window.open(url, '_blank');
496         });
497     }
498
499     showOrder(rows: any[]) {
500         // Doesn't work in Typescript currently without compiler option:
501         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
502         const bibIds = Array.from(
503           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
504         bibIds.forEach( bibId => {
505           const url =
506               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
507           window.open(url, '_blank');
508         });
509     }
510
511     addVolume(rows: any[]) {
512         const bibIds = Array.from(
513           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
514         bibIds.forEach( bibId => {
515           this.holdings.spawnAddHoldingsUi(bibId);
516         });
517     }
518
519     showTitle(rows: any[]) {
520         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
521         bibIds.forEach( bibId => {
522           // const url = '/eg/staff/cat/catalog/record/' + bibId;
523           const url = '/eg2/staff/catalog/record/' + bibId;
524           window.open(url, '_blank');
525         });
526     }
527
528     showManageDialog(rows: any[]) {
529         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
530         if (holdIds.length > 0) {
531             this.manageDialog.holdIds = holdIds;
532             this.manageDialog.open({size: 'lg'}).subscribe(
533                 rowsModified => {
534                     if (rowsModified) {
535                         this.holdsGrid.reload();
536                     }
537                 }
538             );
539         }
540     }
541
542     showTransferDialog(rows: any[]) {
543         const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
544         if (holdIds.length > 0) {
545             this.transferDialog.holdIds = holdIds;
546             this.transferDialog.open({}).subscribe(
547                 rowsModified => {
548                     if (rowsModified) {
549                         this.holdsGrid.reload();
550                     }
551                 }
552             );
553         }
554     }
555
556     async showMarkDamagedDialog(rows: any[]) {
557         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
558         if (copyIds.length === 0) { return; }
559
560         let rowsModified = false;
561
562         const markNext = async(ids: number[]) => {
563             if (ids.length === 0) {
564                 return Promise.resolve();
565             }
566
567             this.markDamagedDialog.copyId = ids.pop();
568             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
569                 ok => {
570                     if (ok) { rowsModified = true; }
571                     return markNext(ids);
572                 },
573                 dismiss => markNext(ids)
574             );
575         };
576
577         await markNext(copyIds);
578         if (rowsModified) {
579             this.holdsGrid.reload();
580         }
581     }
582
583     showMarkMissingDialog(rows: any[]) {
584         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
585         if (copyIds.length > 0) {
586             this.markMissingDialog.copyIds = copyIds;
587             this.markMissingDialog.open({}).subscribe(
588                 rowsModified => {
589                     if (rowsModified) {
590                         this.holdsGrid.reload();
591                     }
592                 }
593             );
594         }
595     }
596
597     showMarkDiscardDialog(rows: any[]) {
598         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
599         if (copyIds.length > 0) {
600             this.markDiscardDialog.copyIds = copyIds;
601             this.markDiscardDialog.open({}).subscribe(
602                 rowsModified => {
603                     if (rowsModified) {
604                         this.holdsGrid.reload();
605                     }
606                 }
607             );
608         }
609     }
610
611
612     showRetargetDialog(rows: any[]) {
613         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
614         if (holdIds.length > 0) {
615             this.retargetDialog.holdIds = holdIds;
616             this.retargetDialog.open({}).subscribe(
617                 rowsModified => {
618                     if (rowsModified) {
619                         this.holdsGrid.reload();
620                     }
621                 }
622             );
623         }
624     }
625
626     showCancelDialog(rows: any[]) {
627         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
628         if (holdIds.length > 0) {
629             this.cancelDialog.holdIds = holdIds;
630             this.cancelDialog.open({}).subscribe(
631                 rowsModified => {
632                     if (rowsModified) {
633                         this.holdsGrid.reload();
634                     }
635                 }
636             );
637         }
638     }
639
640     showUncancelDialog(rows: any[]) {
641         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
642         if (holdIds.length === 0) { return; }
643         this.uncancelHoldCount = holdIds.length;
644
645         this.uncancelDialog.open().subscribe(confirmed => {
646             if (!confirmed) { return; }
647             this.progressDialog.open();
648
649             from(holdIds).pipe(concatMap(holdId => {
650                 return this.net.request(
651                     'open-ils.circ',
652                     'open-ils.circ.hold.uncancel',
653                     this.auth.token(), holdId
654                 );
655             })).subscribe(
656                 resp => {
657                     if (Number(resp) !== 1) {
658                         console.error('Failed uncanceling hold', resp);
659                     }
660                 },
661                 null,
662                 () => {
663                     this.progressDialog.close();
664                     this.holdsGrid.reload();
665                 }
666             );
667         });
668     }
669
670     printHolds() {
671         // Request a page with no limit to get all of the wide holds for
672         // printing.  Call requestPage() directly instead of grid.reload()
673         // since we may already have the data.
674
675         const pager = new Pager();
676         pager.offset = 0;
677         pager.limit = null;
678
679         if (this.gridDataSource.sort.length === 0) {
680             this.gridDataSource.sort = this.defaultSort;
681         }
682
683         this.gridDataSource.requestPage(pager).then(() => {
684             if (this.gridDataSource.data.length > 0) {
685                 this.printer.print({
686                     templateName: this.printTemplate || 'holds_for_bib',
687                     contextData: this.gridDataSource.data,
688                     printContext: 'default'
689                 });
690             }
691         });
692     }
693
694     isCopyHold(holdData: any): boolean {
695         if (holdData && holdData.hold_type) {
696             return holdData.hold_type.match(/C|R|F/) !== null;
697         }
698         return false;
699     }
700 }
701
702
703
704