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