]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1904036 place new hold button/action
[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         };
228     }
229
230     // Returns true after all data/settings/etc required to render the
231     // grid have been fetched.
232     initComplete(): boolean {
233         return this.enablePreFetch !== null;
234     }
235
236     pickupLibChanged(org: IdlObject) {
237         this.pickupLib = org;
238         this.holdsGrid.reload();
239     }
240
241     pullListOrgChanged(org: IdlObject) {
242         this.pullListOrg = org.id();
243         this.holdsGrid.reload();
244     }
245
246     preFetchHolds(apply: boolean) {
247         this.enablePreFetch = apply;
248
249         if (apply) {
250             setTimeout(() => this.holdsGrid.reload());
251         }
252
253         if (this.preFetchSetting) {
254             // fire and forget
255             this.store.setItem(this.preFetchSetting, apply);
256         }
257     }
258
259     applyFilters(): any {
260
261         const filters: any = {};
262
263         if (this.pullListOrg) {
264             filters.cancel_time = null;
265             filters.capture_time = null;
266             filters.frozen = 'f';
267
268             // cp.* fields are set for copy-level holds even if they
269             // have no current_copy.  Make sure current_copy is set.
270             filters.current_copy = {'is not': null};
271
272             // There are aliases for these (cp_status, cp_circ_lib),
273             // but the API complains when I use them.
274             filters['cp.status'] = [0, 7];
275             filters['cp.circ_lib'] = this.pullListOrg;
276
277             return filters;
278         }
279
280         if (this._showFulfilledSince) {
281             filters.fulfillment_time = this._showFulfilledSince.toISOString();
282         } else {
283             filters.fulfillment_time = null;
284         }
285
286         if (this._showCanceledSince) {
287             filters.cancel_time = this._showCanceledSince.toISOString();
288         } else {
289             filters.cancel_time = null;
290         }
291
292         if (this.hopeless) {
293           filters['hopeless_holds'] = {
294             'start_date' : this._showHopelessAfter
295               ? (
296                   // FIXME -- consistency desired, string or object
297                   typeof this._showHopelessAfter === 'object'
298                   ? this._showHopelessAfter.toISOString()
299                   : this._showHopelessAfter
300                 )
301               : '1970-01-01T00:00:00.000Z',
302             'end_date' : this._showHopelessBefore
303               ? (
304                   // FIXME -- consistency desired, string or object
305                   typeof this._showHopelessBefore === 'object'
306                   ? this._showHopelessBefore.toISOString()
307                   : this._showHopelessBefore
308                 )
309               : (new Date()).toISOString()
310           };
311         }
312
313         if (this.pickupLib) {
314             filters.pickup_lib =
315                 this.org.descendants(this.pickupLib, true);
316         }
317
318         if (this.recordId) {
319             filters.record_id = this.recordId;
320         }
321
322         if (this.patronId) {
323             filters.usr_id = this.patronId;
324         }
325
326         return filters;
327     }
328
329     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
330
331         // We need at least one filter.
332         if (!this.recordId && !this.pickupLib && !this.patronId && !this.pullListOrg) {
333             return of([]);
334         }
335
336         const filters = this.applyFilters();
337
338         const orderBy: any = [];
339         if (sort.length > 0) {
340             sort.forEach(obj => {
341                 const subObj: any = {};
342                 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
343                 orderBy.push(subObj);
344             });
345         }
346
347         const limit = this.enablePreFetch ? null : pager.limit;
348         const offset = this.enablePreFetch ? 0 : pager.offset;
349         const options: any = {};
350         if (this.showRecentlyCanceled) {
351             options.recently_canceled = true;
352         } else {
353             filters.cancel_time = null;
354         }
355
356         let observer: Observer<any>;
357         const observable = new Observable(obs => observer = obs);
358
359         this.progressDialog.open();
360         this.progressDialog.update({value: 0, max: 1});
361         let first = true;
362         let loadCount = 0;
363         this.net.request(
364             'open-ils.circ',
365             'open-ils.circ.hold.wide_hash.stream',
366             this.auth.token(), filters, orderBy, limit, offset, options
367         ).subscribe(
368             holdData => {
369
370                 if (first) { // First response is the hold count.
371                     this.holdsCount = Number(holdData);
372                     first = false;
373
374                 } else { // Subsequent responses are hold data blobs
375
376                     this.progressDialog.update(
377                         {value: ++loadCount, max: this.holdsCount});
378
379                     observer.next(holdData);
380                 }
381             },
382             err => {
383                 this.progressDialog.close();
384                 observer.error(err);
385             },
386             ()  => {
387                 this.progressDialog.close();
388                 observer.complete();
389             }
390         );
391
392         return observable;
393     }
394
395     metaRecordHoldsSelected(rows: IdlObject[]) {
396         let found = false;
397         rows.forEach( row => {
398            if (row.hold_type === 'M') {
399              found = true;
400            }
401         });
402         return found;
403     }
404
405     nonTitleHoldsSelected(rows: IdlObject[]) {
406         let found = false;
407         rows.forEach( row => {
408            if (row.hold_type !== 'T') {
409              found = true;
410            }
411         });
412         return found;
413     }
414
415     showDetails(rows: any[]) {
416         this.showDetail(rows[0]);
417     }
418
419     showHoldsForTitle(rows: any[]) {
420         if (rows.length === 0) { return; }
421
422         const url = this.ngLocation.prepareExternalUrl(
423             `/staff/catalog/record/${rows[0].record_id}/holds`);
424
425         window.open(url, '_blank');
426     }
427
428     showDetail(row: any) {
429         if (row) {
430             this.mode = 'detail';
431             this.detailHold = row;
432         }
433     }
434
435     showManager(rows: any[]) {
436         if (rows.length) {
437             this.mode = 'manage';
438             this.editHolds = rows.map(r => r.id);
439         }
440     }
441
442     handleModify(rowsModified: boolean) {
443         this.mode = 'list';
444
445         if (rowsModified) {
446             // give the grid a chance to render then ask it to reload
447             setTimeout(() => this.holdsGrid.reload());
448         }
449     }
450
451
452
453     showRecentCircs(rows: any[]) {
454         const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
455         copyIds.forEach( copyId => {
456             const url =
457                 '/eg/staff/cat/item/' + copyId + '/circ_list';
458             window.open(url, '_blank');
459         });
460     }
461
462     showPatron(rows: any[]) {
463         const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
464         usrIds.forEach( usrId => {
465             const url =
466                 '/eg/staff/circ/patron/' + usrId + '/checkout';
467             window.open(url, '_blank');
468         });
469     }
470
471     showOrder(rows: any[]) {
472         // Doesn't work in Typescript currently without compiler option:
473         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
474         const bibIds = Array.from(
475           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
476         bibIds.forEach( bibId => {
477           const url =
478               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
479           window.open(url, '_blank');
480         });
481     }
482
483     addVolume(rows: any[]) {
484         const bibIds = Array.from(
485           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
486         bibIds.forEach( bibId => {
487           this.holdings.spawnAddHoldingsUi(bibId);
488         });
489     }
490
491     showTitle(rows: any[]) {
492         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
493         bibIds.forEach( bibId => {
494           // const url = '/eg/staff/cat/catalog/record/' + bibId;
495           const url = '/eg2/staff/catalog/record/' + bibId;
496           window.open(url, '_blank');
497         });
498     }
499
500     showManageDialog(rows: any[]) {
501         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
502         if (holdIds.length > 0) {
503             this.manageDialog.holdIds = holdIds;
504             this.manageDialog.open({size: 'lg'}).subscribe(
505                 rowsModified => {
506                     if (rowsModified) {
507                         this.holdsGrid.reload();
508                     }
509                 }
510             );
511         }
512     }
513
514     showTransferDialog(rows: any[]) {
515         const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
516         if (holdIds.length > 0) {
517             this.transferDialog.holdIds = holdIds;
518             this.transferDialog.open({}).subscribe(
519                 rowsModified => {
520                     if (rowsModified) {
521                         this.holdsGrid.reload();
522                     }
523                 }
524             );
525         }
526     }
527
528     async showMarkDamagedDialog(rows: any[]) {
529         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
530         if (copyIds.length === 0) { return; }
531
532         let rowsModified = false;
533
534         const markNext = async(ids: number[]) => {
535             if (ids.length === 0) {
536                 return Promise.resolve();
537             }
538
539             this.markDamagedDialog.copyId = ids.pop();
540             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
541                 ok => {
542                     if (ok) { rowsModified = true; }
543                     return markNext(ids);
544                 },
545                 dismiss => markNext(ids)
546             );
547         };
548
549         await markNext(copyIds);
550         if (rowsModified) {
551             this.holdsGrid.reload();
552         }
553     }
554
555     showMarkMissingDialog(rows: any[]) {
556         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
557         if (copyIds.length > 0) {
558             this.markMissingDialog.copyIds = copyIds;
559             this.markMissingDialog.open({}).subscribe(
560                 rowsModified => {
561                     if (rowsModified) {
562                         this.holdsGrid.reload();
563                     }
564                 }
565             );
566         }
567     }
568
569     showMarkDiscardDialog(rows: any[]) {
570         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
571         if (copyIds.length > 0) {
572             this.markDiscardDialog.copyIds = copyIds;
573             this.markDiscardDialog.open({}).subscribe(
574                 rowsModified => {
575                     if (rowsModified) {
576                         this.holdsGrid.reload();
577                     }
578                 }
579             );
580         }
581     }
582
583
584     showRetargetDialog(rows: any[]) {
585         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
586         if (holdIds.length > 0) {
587             this.retargetDialog.holdIds = holdIds;
588             this.retargetDialog.open({}).subscribe(
589                 rowsModified => {
590                     if (rowsModified) {
591                         this.holdsGrid.reload();
592                     }
593                 }
594             );
595         }
596     }
597
598     showCancelDialog(rows: any[]) {
599         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
600         if (holdIds.length > 0) {
601             this.cancelDialog.holdIds = holdIds;
602             this.cancelDialog.open({}).subscribe(
603                 rowsModified => {
604                     if (rowsModified) {
605                         this.holdsGrid.reload();
606                     }
607                 }
608             );
609         }
610     }
611
612     printHolds() {
613         // Request a page with no limit to get all of the wide holds for
614         // printing.  Call requestPage() directly instead of grid.reload()
615         // since we may already have the data.
616
617         const pager = new Pager();
618         pager.offset = 0;
619         pager.limit = null;
620
621         if (this.gridDataSource.sort.length === 0) {
622             this.gridDataSource.sort = this.defaultSort;
623         }
624
625         this.gridDataSource.requestPage(pager).then(() => {
626             if (this.gridDataSource.data.length > 0) {
627                 this.printer.print({
628                     templateName: this.printTemplate || 'holds_for_bib',
629                     contextData: this.gridDataSource.data,
630                     printContext: 'default'
631                 });
632             }
633         });
634     }
635
636     isCopyHold(holdData: any): boolean {
637         return holdData.hold_type.match(/C|R|F/) !== null;
638     }
639 }
640
641
642
643