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