]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1904036 Ang Patron UI updating non-menu links
[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
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;
115
116     // Bib record ID.
117     _recordId: number;
118     @Input() set recordId(id: number) {
119         this._recordId = id;
120         if (this.initDone) { // reload on update
121             this.holdsGrid.reload();
122         }
123     }
124
125     get recordId(): number {
126         return this._recordId;
127     }
128
129     _patronId: number;
130     @Input() set patronId(id: number) {
131         this._patronId = id;
132         if (this.initDone) {
133             this.holdsGrid.reload();
134         }
135     }
136     get patronId(): number {
137         return this._patronId;
138     }
139
140     // If true, show recently canceled holds only.
141     @Input() showRecentlyCanceled = false;
142
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();
150         }
151     }
152     get showFulfilledSince(): Date {
153         return this._showFulfilledSince;
154     }
155
156
157     cellTextGenerator: GridCellTextGenerator;
158
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();
165         }
166     }
167
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();
174         }
175     }
176
177     // Notify the caller the place hold button was clicked.
178     @Output() placeHoldRequested: EventEmitter<void> = new EventEmitter<void>();
179
180     constructor(
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
188     ) {
189         this.gridDataSource = new GridDataSource();
190         this.enablePreFetch = null;
191     }
192
193     ngOnInit() {
194         this.initDone = true;
195         this.pickupLib = this.org.get(this.initialPickupLib);
196
197         if (this.preFetchSetting) {
198             this.store.getItem(this.preFetchSetting).then(
199                 applied => this.enablePreFetch = Boolean(applied)
200             );
201         } else {
202             this.enablePreFetch = false;
203         }
204
205         if (!this.defaultSort) {
206             if (this.pullListOrg) {
207
208                 this.defaultSort = [
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"
214                 ];
215
216             } else {
217                 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
218             }
219         }
220
221         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
222
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.
228                 return of([]);
229             }
230
231             sort = sort.length > 0 ? sort : this.defaultSort;
232             return this.fetchHolds(pager, sort);
233         };
234
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
243         };
244     }
245
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;
250     }
251
252     pickupLibChanged(org: IdlObject) {
253         this.pickupLib = org;
254         this.holdsGrid.reload();
255     }
256
257     pullListOrgChanged(org: IdlObject) {
258         this.pullListOrg = org.id();
259         this.holdsGrid.reload();
260     }
261
262     preFetchHolds(apply: boolean) {
263         this.enablePreFetch = apply;
264
265         if (apply) {
266             setTimeout(() => this.holdsGrid.reload());
267         }
268
269         if (this.preFetchSetting) {
270             // fire and forget
271             this.store.setItem(this.preFetchSetting, apply);
272         }
273     }
274
275     applyFilters(): any {
276
277         const filters: any = {};
278
279         if (this.pullListOrg) {
280             filters.cancel_time = null;
281             filters.capture_time = null;
282             filters.frozen = 'f';
283
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};
287
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;
292
293             return filters;
294         }
295
296         if (this._showFulfilledSince) {
297             filters.fulfillment_time = this._showFulfilledSince.toISOString();
298         } else {
299             filters.fulfillment_time = null;
300         }
301
302
303         if (this.hopeless) {
304           filters['hopeless_holds'] = {
305             'start_date' : this._showHopelessAfter
306               ? (
307                   // FIXME -- consistency desired, string or object
308                   typeof this._showHopelessAfter === 'object'
309                   ? this._showHopelessAfter.toISOString()
310                   : this._showHopelessAfter
311                 )
312               : '1970-01-01T00:00:00.000Z',
313             'end_date' : this._showHopelessBefore
314               ? (
315                   // FIXME -- consistency desired, string or object
316                   typeof this._showHopelessBefore === 'object'
317                   ? this._showHopelessBefore.toISOString()
318                   : this._showHopelessBefore
319                 )
320               : (new Date()).toISOString()
321           };
322         }
323
324         if (this.pickupLib) {
325             filters.pickup_lib =
326                 this.org.descendants(this.pickupLib, true);
327         }
328
329         if (this.recordId) {
330             filters.record_id = this.recordId;
331         }
332
333         if (this.patronId) {
334             filters.usr_id = this.patronId;
335         }
336
337         return filters;
338     }
339
340     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
341
342         // We need at least one filter.
343         if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
344             return of([]);
345         }
346
347         const filters = this.applyFilters();
348
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);
355             });
356         }
357
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;
363         } else {
364             filters.cancel_time = null;
365         }
366
367         let observer: Observer<any>;
368         const observable = new Observable(obs => observer = obs);
369
370         if (!this.noLoadProgress) {
371             // Note remaining dialog actions have no impact
372             this.progressDialog.open();
373         }
374
375         this.progressDialog.update({value: 0, max: 1});
376
377         let first = true;
378         let loadCount = 0;
379         this.net.request(
380             'open-ils.circ',
381             'open-ils.circ.hold.wide_hash.stream',
382             this.auth.token(), filters, orderBy, limit, offset, options
383         ).subscribe(
384             holdData => {
385
386                 if (first) { // First response is the hold count.
387                     this.holdsCount = Number(holdData);
388                     first = false;
389
390                 } else { // Subsequent responses are hold data blobs
391
392                     this.progressDialog.update(
393                         {value: ++loadCount, max: this.holdsCount});
394
395                     observer.next(holdData);
396                 }
397             },
398             err => {
399                 this.progressDialog.close();
400                 observer.error(err);
401             },
402             ()  => {
403                 this.progressDialog.close();
404                 observer.complete();
405             }
406         );
407
408         return observable;
409     }
410
411     metaRecordHoldsSelected(rows: IdlObject[]) {
412         let found = false;
413         rows.forEach( row => {
414            if (row.hold_type === 'M') {
415              found = true;
416            }
417         });
418         return found;
419     }
420
421     nonTitleHoldsSelected(rows: IdlObject[]) {
422         let found = false;
423         rows.forEach( row => {
424            if (row.hold_type !== 'T') {
425              found = true;
426            }
427         });
428         return found;
429     }
430
431     showDetails(rows: any[]) {
432         this.showDetail(rows[0]);
433     }
434
435     showHoldsForTitle(rows: any[]) {
436         if (rows.length === 0) { return; }
437
438         const url = this.ngLocation.prepareExternalUrl(
439             `/staff/catalog/record/${rows[0].record_id}/holds`);
440
441         window.open(url, '_blank');
442     }
443
444     showDetail(row: any) {
445         if (row) {
446             this.mode = 'detail';
447             this.detailHold = row;
448         }
449     }
450
451     showManager(rows: any[]) {
452         if (rows.length) {
453             this.mode = 'manage';
454             this.editHolds = rows.map(r => r.id);
455         }
456     }
457
458     handleModify(rowsModified: boolean) {
459         this.mode = 'list';
460
461         if (rowsModified) {
462             // give the grid a chance to render then ask it to reload
463             setTimeout(() => this.holdsGrid.reload());
464         }
465     }
466
467
468
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 => {
472             const url =
473                 '/eg/staff/cat/item/' + copyId + '/circ_list';
474             window.open(url, '_blank');
475         });
476     }
477
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 => {
481             window.open(
482                 this.ngLocation.prepareExternalUrl(
483                    '/staff/circ/patron/' + usrId + '/checkout'
484                 )
485             );
486         });
487     }
488
489     showOrder(rows: any[]) {
490         // Doesn't work in Typescript currently without compiler option:
491         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
492         const bibIds = Array.from(
493           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
494         bibIds.forEach( bibId => {
495           const url =
496               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
497           window.open(url, '_blank');
498         });
499     }
500
501     addVolume(rows: any[]) {
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           this.holdings.spawnAddHoldingsUi(bibId);
506         });
507     }
508
509     showTitle(rows: any[]) {
510         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
511         bibIds.forEach( bibId => {
512           // const url = '/eg/staff/cat/catalog/record/' + bibId;
513           const url = '/eg2/staff/catalog/record/' + bibId;
514           window.open(url, '_blank');
515         });
516     }
517
518     showManageDialog(rows: any[]) {
519         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
520         if (holdIds.length > 0) {
521             this.manageDialog.holdIds = holdIds;
522             this.manageDialog.open({size: 'lg'}).subscribe(
523                 rowsModified => {
524                     if (rowsModified) {
525                         this.holdsGrid.reload();
526                     }
527                 }
528             );
529         }
530     }
531
532     showTransferDialog(rows: any[]) {
533         const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
534         if (holdIds.length > 0) {
535             this.transferDialog.holdIds = holdIds;
536             this.transferDialog.open({}).subscribe(
537                 rowsModified => {
538                     if (rowsModified) {
539                         this.holdsGrid.reload();
540                     }
541                 }
542             );
543         }
544     }
545
546     async showMarkDamagedDialog(rows: any[]) {
547         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
548         if (copyIds.length === 0) { return; }
549
550         let rowsModified = false;
551
552         const markNext = async(ids: number[]) => {
553             if (ids.length === 0) {
554                 return Promise.resolve();
555             }
556
557             this.markDamagedDialog.copyId = ids.pop();
558             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
559                 ok => {
560                     if (ok) { rowsModified = true; }
561                     return markNext(ids);
562                 },
563                 dismiss => markNext(ids)
564             );
565         };
566
567         await markNext(copyIds);
568         if (rowsModified) {
569             this.holdsGrid.reload();
570         }
571     }
572
573     showMarkMissingDialog(rows: any[]) {
574         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
575         if (copyIds.length > 0) {
576             this.markMissingDialog.copyIds = copyIds;
577             this.markMissingDialog.open({}).subscribe(
578                 rowsModified => {
579                     if (rowsModified) {
580                         this.holdsGrid.reload();
581                     }
582                 }
583             );
584         }
585     }
586
587     showMarkDiscardDialog(rows: any[]) {
588         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
589         if (copyIds.length > 0) {
590             this.markDiscardDialog.copyIds = copyIds;
591             this.markDiscardDialog.open({}).subscribe(
592                 rowsModified => {
593                     if (rowsModified) {
594                         this.holdsGrid.reload();
595                     }
596                 }
597             );
598         }
599     }
600
601
602     showRetargetDialog(rows: any[]) {
603         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
604         if (holdIds.length > 0) {
605             this.retargetDialog.holdIds = holdIds;
606             this.retargetDialog.open({}).subscribe(
607                 rowsModified => {
608                     if (rowsModified) {
609                         this.holdsGrid.reload();
610                     }
611                 }
612             );
613         }
614     }
615
616     showCancelDialog(rows: any[]) {
617         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
618         if (holdIds.length > 0) {
619             this.cancelDialog.holdIds = holdIds;
620             this.cancelDialog.open({}).subscribe(
621                 rowsModified => {
622                     if (rowsModified) {
623                         this.holdsGrid.reload();
624                     }
625                 }
626             );
627         }
628     }
629
630     showUncancelDialog(rows: any[]) {
631         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
632         if (holdIds.length === 0) { return; }
633         this.uncancelHoldCount = holdIds.length;
634
635         this.uncancelDialog.open().subscribe(confirmed => {
636             if (!confirmed) { return; }
637             this.progressDialog.open();
638
639             from(holdIds).pipe(concatMap(holdId => {
640                 return this.net.request(
641                     'open-ils.circ',
642                     'open-ils.circ.hold.uncancel',
643                     this.auth.token(), holdId
644                 );
645             })).subscribe(
646                 resp => {
647                     if (Number(resp) !== 1) {
648                         console.error('Failed uncanceling hold', resp);
649                     }
650                 },
651                 null,
652                 () => {
653                     this.progressDialog.close();
654                     this.holdsGrid.reload();
655                 }
656             );
657         });
658     }
659
660     printHolds() {
661         // Request a page with no limit to get all of the wide holds for
662         // printing.  Call requestPage() directly instead of grid.reload()
663         // since we may already have the data.
664
665         const pager = new Pager();
666         pager.offset = 0;
667         pager.limit = null;
668
669         if (this.gridDataSource.sort.length === 0) {
670             this.gridDataSource.sort = this.defaultSort;
671         }
672
673         this.gridDataSource.requestPage(pager).then(() => {
674             if (this.gridDataSource.data.length > 0) {
675                 this.printer.print({
676                     templateName: this.printTemplate || 'holds_for_bib',
677                     contextData: this.gridDataSource.data,
678                     printContext: 'default'
679                 });
680             }
681         });
682     }
683
684     isCopyHold(holdData: any): boolean {
685         return holdData.hold_type.match(/C|R|F/) !== null;
686     }
687 }
688
689
690
691