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