]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1904036 Mark damaged; canceled holds display repair
[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 = 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: any = {};
343         if (this.showRecentlyCanceled) {
344             options.recently_canceled = true;
345         } else {
346             filters.cancel_time = null;
347         }
348
349         let observer: Observer<any>;
350         const observable = new Observable(obs => observer = obs);
351
352         this.progressDialog.open();
353         this.progressDialog.update({value: 0, max: 1});
354         let first = true;
355         let loadCount = 0;
356         this.net.request(
357             'open-ils.circ',
358             'open-ils.circ.hold.wide_hash.stream',
359             this.auth.token(), filters, orderBy, limit, offset, options
360         ).subscribe(
361             holdData => {
362
363                 if (first) { // First response is the hold count.
364                     this.holdsCount = Number(holdData);
365                     first = false;
366
367                 } else { // Subsequent responses are hold data blobs
368
369                     this.progressDialog.update(
370                         {value: ++loadCount, max: this.holdsCount});
371
372                     observer.next(holdData);
373                 }
374             },
375             err => {
376                 this.progressDialog.close();
377                 observer.error(err);
378             },
379             ()  => {
380                 this.progressDialog.close();
381                 observer.complete();
382             }
383         );
384
385         return observable;
386     }
387
388     metaRecordHoldsSelected(rows: IdlObject[]) {
389         let found = false;
390         rows.forEach( row => {
391            if (row.hold_type === 'M') {
392              found = true;
393            }
394         });
395         return found;
396     }
397
398     nonTitleHoldsSelected(rows: IdlObject[]) {
399         let found = false;
400         rows.forEach( row => {
401            if (row.hold_type !== 'T') {
402              found = true;
403            }
404         });
405         return found;
406     }
407
408     showDetails(rows: any[]) {
409         this.showDetail(rows[0]);
410     }
411
412     showHoldsForTitle(rows: any[]) {
413         if (rows.length === 0) { return; }
414
415         const url = this.ngLocation.prepareExternalUrl(
416             `/staff/catalog/record/${rows[0].record_id}/holds`);
417
418         window.open(url, '_blank');
419     }
420
421     showDetail(row: any) {
422         if (row) {
423             this.mode = 'detail';
424             this.detailHold = row;
425         }
426     }
427
428     showManager(rows: any[]) {
429         if (rows.length) {
430             this.mode = 'manage';
431             this.editHolds = rows.map(r => r.id);
432         }
433     }
434
435     handleModify(rowsModified: boolean) {
436         this.mode = 'list';
437
438         if (rowsModified) {
439             // give the grid a chance to render then ask it to reload
440             setTimeout(() => this.holdsGrid.reload());
441         }
442     }
443
444
445
446     showRecentCircs(rows: any[]) {
447         const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
448         copyIds.forEach( copyId => {
449             const url =
450                 '/eg/staff/cat/item/' + copyId + '/circ_list';
451             window.open(url, '_blank');
452         });
453     }
454
455     showPatron(rows: any[]) {
456         const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
457         usrIds.forEach( usrId => {
458             const url =
459                 '/eg/staff/circ/patron/' + usrId + '/checkout';
460             window.open(url, '_blank');
461         });
462     }
463
464     showOrder(rows: any[]) {
465         // Doesn't work in Typescript currently without compiler option:
466         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
467         const bibIds = Array.from(
468           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
469         bibIds.forEach( bibId => {
470           const url =
471               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
472           window.open(url, '_blank');
473         });
474     }
475
476     addVolume(rows: any[]) {
477         const bibIds = Array.from(
478           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
479         bibIds.forEach( bibId => {
480           this.holdings.spawnAddHoldingsUi(bibId);
481         });
482     }
483
484     showTitle(rows: any[]) {
485         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
486         bibIds.forEach( bibId => {
487           // const url = '/eg/staff/cat/catalog/record/' + bibId;
488           const url = '/eg2/staff/catalog/record/' + bibId;
489           window.open(url, '_blank');
490         });
491     }
492
493     showManageDialog(rows: any[]) {
494         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
495         if (holdIds.length > 0) {
496             this.manageDialog.holdIds = holdIds;
497             this.manageDialog.open({size: 'lg'}).subscribe(
498                 rowsModified => {
499                     if (rowsModified) {
500                         this.holdsGrid.reload();
501                     }
502                 }
503             );
504         }
505     }
506
507     showTransferDialog(rows: any[]) {
508         const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
509         if (holdIds.length > 0) {
510             this.transferDialog.holdIds = holdIds;
511             this.transferDialog.open({}).subscribe(
512                 rowsModified => {
513                     if (rowsModified) {
514                         this.holdsGrid.reload();
515                     }
516                 }
517             );
518         }
519     }
520
521     async showMarkDamagedDialog(rows: any[]) {
522         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
523         if (copyIds.length === 0) { return; }
524
525         let rowsModified = false;
526
527         const markNext = async(ids: number[]) => {
528             if (ids.length === 0) {
529                 return Promise.resolve();
530             }
531
532             this.markDamagedDialog.copyId = ids.pop();
533             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
534                 ok => {
535                     if (ok) { rowsModified = true; }
536                     return markNext(ids);
537                 },
538                 dismiss => markNext(ids)
539             );
540         };
541
542         await markNext(copyIds);
543         if (rowsModified) {
544             this.holdsGrid.reload();
545         }
546     }
547
548     showMarkMissingDialog(rows: any[]) {
549         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
550         if (copyIds.length > 0) {
551             this.markMissingDialog.copyIds = copyIds;
552             this.markMissingDialog.open({}).subscribe(
553                 rowsModified => {
554                     if (rowsModified) {
555                         this.holdsGrid.reload();
556                     }
557                 }
558             );
559         }
560     }
561
562     showMarkDiscardDialog(rows: any[]) {
563         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
564         if (copyIds.length > 0) {
565             this.markDiscardDialog.copyIds = copyIds;
566             this.markDiscardDialog.open({}).subscribe(
567                 rowsModified => {
568                     if (rowsModified) {
569                         this.holdsGrid.reload();
570                     }
571                 }
572             );
573         }
574     }
575
576
577     showRetargetDialog(rows: any[]) {
578         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
579         if (holdIds.length > 0) {
580             this.retargetDialog.holdIds = holdIds;
581             this.retargetDialog.open({}).subscribe(
582                 rowsModified => {
583                     if (rowsModified) {
584                         this.holdsGrid.reload();
585                     }
586                 }
587             );
588         }
589     }
590
591     showCancelDialog(rows: any[]) {
592         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
593         if (holdIds.length > 0) {
594             this.cancelDialog.holdIds = holdIds;
595             this.cancelDialog.open({}).subscribe(
596                 rowsModified => {
597                     if (rowsModified) {
598                         this.holdsGrid.reload();
599                     }
600                 }
601             );
602         }
603     }
604
605     printHolds() {
606         // Request a page with no limit to get all of the wide holds for
607         // printing.  Call requestPage() directly instead of grid.reload()
608         // since we may already have the data.
609
610         const pager = new Pager();
611         pager.offset = 0;
612         pager.limit = null;
613
614         if (this.gridDataSource.sort.length === 0) {
615             this.gridDataSource.sort = this.defaultSort;
616         }
617
618         this.gridDataSource.requestPage(pager).then(() => {
619             if (this.gridDataSource.data.length > 0) {
620                 this.printer.print({
621                     templateName: this.printTemplate || 'holds_for_bib',
622                     contextData: this.gridDataSource.data,
623                     printContext: 'default'
624                 });
625             }
626         });
627     }
628
629     isCopyHold(holdData: any): boolean {
630         return holdData.hold_type.match(/C|R|F/) !== null;
631     }
632 }
633
634
635
636