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