]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP2000482 Bootstrap 5 continued
[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             const url =
482                 '/eg/staff/circ/patron/' + usrId + '/checkout';
483             window.open(url, '_blank');
484         });
485     }
486
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 => {
493           const url =
494               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
495           window.open(url, '_blank');
496         });
497     }
498
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);
504         });
505     }
506
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');
513         });
514     }
515
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(
521                 rowsModified => {
522                     if (rowsModified) {
523                         this.holdsGrid.reload();
524                     }
525                 }
526             );
527         }
528     }
529
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(
535                 rowsModified => {
536                     if (rowsModified) {
537                         this.holdsGrid.reload();
538                     }
539                 }
540             );
541         }
542     }
543
544     async showMarkDamagedDialog(rows: any[]) {
545         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
546         if (copyIds.length === 0) { return; }
547
548         let rowsModified = false;
549
550         const markNext = async(ids: number[]) => {
551             if (ids.length === 0) {
552                 return Promise.resolve();
553             }
554
555             this.markDamagedDialog.copyId = ids.pop();
556             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
557                 ok => {
558                     if (ok) { rowsModified = true; }
559                     return markNext(ids);
560                 },
561                 dismiss => markNext(ids)
562             );
563         };
564
565         await markNext(copyIds);
566         if (rowsModified) {
567             this.holdsGrid.reload();
568         }
569     }
570
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(
576                 rowsModified => {
577                     if (rowsModified) {
578                         this.holdsGrid.reload();
579                     }
580                 }
581             );
582         }
583     }
584
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(
590                 rowsModified => {
591                     if (rowsModified) {
592                         this.holdsGrid.reload();
593                     }
594                 }
595             );
596         }
597     }
598
599
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(
605                 rowsModified => {
606                     if (rowsModified) {
607                         this.holdsGrid.reload();
608                     }
609                 }
610             );
611         }
612     }
613
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(
619                 rowsModified => {
620                     if (rowsModified) {
621                         this.holdsGrid.reload();
622                     }
623                 }
624             );
625         }
626     }
627
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;
632
633         this.uncancelDialog.open().subscribe(confirmed => {
634             if (!confirmed) { return; }
635             this.progressDialog.open();
636
637             from(holdIds).pipe(concatMap(holdId => {
638                 return this.net.request(
639                     'open-ils.circ',
640                     'open-ils.circ.hold.uncancel',
641                     this.auth.token(), holdId
642                 );
643             })).subscribe(
644                 resp => {
645                     if (Number(resp) !== 1) {
646                         console.error('Failed uncanceling hold', resp);
647                     }
648                 },
649                 null,
650                 () => {
651                     this.progressDialog.close();
652                     this.holdsGrid.reload();
653                 }
654             );
655         });
656     }
657
658     printHolds() {
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.
662
663         const pager = new Pager();
664         pager.offset = 0;
665         pager.limit = null;
666
667         if (this.gridDataSource.sort.length === 0) {
668             this.gridDataSource.sort = this.defaultSort;
669         }
670
671         this.gridDataSource.requestPage(pager).then(() => {
672             if (this.gridDataSource.data.length > 0) {
673                 this.printer.print({
674                     templateName: this.printTemplate || 'holds_for_bib',
675                     contextData: this.gridDataSource.data,
676                     printContext: 'default'
677                 });
678             }
679         });
680     }
681
682     isCopyHold(holdData: any): boolean {
683         if (holdData && holdData.hold_type) {
684             return holdData.hold_type.match(/C|R|F/) !== null;
685         }
686         return false;
687     }
688 }
689
690
691
692