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