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