LP1818288 WS Option to pre-fetch record holds
[working/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} 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
22 /** Holds grid with access to detail page and other actions */
23
24 @Component({
25   selector: 'eg-holds-grid',
26   templateUrl: 'grid.component.html'
27 })
28 export class HoldsGridComponent implements OnInit {
29
30     // If either are set/true, the pickup lib selector will display
31     @Input() initialPickupLib: number | IdlObject;
32     @Input() hidePickupLibFilter: boolean;
33
34     // Grid persist key
35     @Input() persistKey: string;
36
37     @Input() preFetchSetting: string;
38         // If set, all holds are fetched on grid load and sorting/paging all
39     // happens in the client.  If false, sorting and paging occur on
40     // the server.
41     enablePreFetch: boolean;
42
43     // How to sort when no sort parameters have been applied
44     // via grid controls.  This uses the eg-grid sort format:
45     // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
46     @Input() defaultSort: any[];
47
48     mode: 'list' | 'detail' | 'manage' = 'list';
49     initDone = false;
50     holdsCount: number;
51     pickupLib: IdlObject;
52     gridDataSource: GridDataSource;
53     detailHold: any;
54     editHolds: number[];
55     transferTarget: number;
56
57     @ViewChild('holdsGrid') private holdsGrid: GridComponent;
58     @ViewChild('progressDialog')
59         private progressDialog: ProgressDialogComponent;
60     @ViewChild('transferDialog')
61         private transferDialog: HoldTransferDialogComponent;
62     @ViewChild('markDamagedDialog')
63         private markDamagedDialog: MarkDamagedDialogComponent;
64     @ViewChild('markMissingDialog')
65         private markMissingDialog: MarkMissingDialogComponent;
66     @ViewChild('retargetDialog')
67         private retargetDialog: HoldRetargetDialogComponent;
68     @ViewChild('cancelDialog')
69         private cancelDialog: HoldCancelDialogComponent;
70     @ViewChild('manageDialog')
71         private manageDialog: HoldManageDialogComponent;
72
73     // Bib record ID.
74     _recordId: number;
75     @Input() set recordId(id: number) {
76         this._recordId = id;
77         if (this.initDone) { // reload on update
78             this.holdsGrid.reload();
79         }
80     }
81
82     _userId: number;
83     @Input() set userId(id: number) {
84         this._userId = id;
85         if (this.initDone) {
86             this.holdsGrid.reload();
87         }
88     }
89
90     // Include holds canceled on or after the provided date.
91     // If no value is passed, canceled holds are not displayed.
92     _showCanceledSince: Date;
93     @Input() set showCanceledSince(show: Date) {
94         this._showCanceledSince = show;
95         if (this.initDone) { // reload on update
96             this.holdsGrid.reload();
97         }
98     }
99
100     // Include holds fulfilled on or after hte provided date.
101     // If no value is passed, fulfilled holds are not displayed.
102     _showFulfilledSince: Date;
103     @Input() set showFulfilledSince(show: Date) {
104         this._showFulfilledSince = show;
105         if (this.initDone) { // reload on update
106             this.holdsGrid.reload();
107         }
108     }
109
110     constructor(
111         private net: NetService,
112         private org: OrgService,
113         private store: ServerStoreService,
114         private auth: AuthService
115     ) {
116         this.gridDataSource = new GridDataSource();
117         this.enablePreFetch = null;
118     }
119
120     ngOnInit() {
121         this.initDone = true;
122         this.pickupLib = this.org.get(this.initialPickupLib);
123
124         if (this.preFetchSetting) {
125
126                 this.store.getItem(this.preFetchSetting).then(
127                     applied => this.enablePreFetch = Boolean(applied)
128                 );
129
130         }
131
132         if (!this.defaultSort) {
133             this.defaultSort = [{name: 'request_time', dir: 'asc'}];
134         }
135
136         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
137             sort = sort.length > 0 ? sort : this.defaultSort;
138             return this.fetchHolds(pager, sort);
139         };
140     }
141
142     // Returns true after all data/settings/etc required to render the
143     // grid have been fetched.
144     initComplete(): boolean {
145         return this.enablePreFetch !== null;
146     }
147
148     pickupLibChanged(org: IdlObject) {
149         this.pickupLib = org;
150         this.holdsGrid.reload();
151     }
152
153     preFetchHolds(apply: boolean) {
154         this.enablePreFetch = apply;
155
156         if (apply) {
157             setTimeout(() => this.holdsGrid.reload());
158         }
159
160         if (this.preFetchSetting) {
161             // fire and forget
162             this.store.setItem(this.preFetchSetting, apply);
163         }
164     }
165
166     applyFilters(): any {
167         const filters: any = {
168             is_staff_request: true,
169             fulfillment_time: this._showFulfilledSince ?
170                 this._showFulfilledSince.toISOString() : null,
171             cancel_time: this._showCanceledSince ?
172                 this._showCanceledSince.toISOString() : null,
173         };
174
175         if (this.pickupLib) {
176             filters.pickup_lib =
177                 this.org.descendants(this.pickupLib, true);
178         }
179
180         if (this._recordId) {
181             filters.record_id = this._recordId;
182         }
183
184         if (this._userId) {
185             filters.usr_id = this._userId;
186         }
187
188         return filters;
189     }
190
191     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
192
193         // We need at least one filter.
194         if (!this._recordId && !this.pickupLib && !this._userId) {
195             return of([]);
196         }
197
198         const filters = this.applyFilters();
199
200         const orderBy: any = [];
201         if (sort.length > 0) {
202             sort.forEach(obj => {
203                 const subObj: any = {};
204                 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
205                 orderBy.push(subObj);
206             });
207         }
208
209         const limit = this.enablePreFetch ? null : pager.limit;
210         const offset = this.enablePreFetch ? 0 : pager.offset;
211
212         let observer: Observer<any>;
213         const observable = new Observable(obs => observer = obs);
214
215         this.progressDialog.open();
216         this.progressDialog.update({value: 0, max: 1});
217         let first = true;
218         let loadCount = 0;
219         this.net.request(
220             'open-ils.circ',
221             'open-ils.circ.hold.wide_hash.stream',
222             this.auth.token(), filters, orderBy, limit, offset
223         ).subscribe(
224             holdData => {
225
226                 if (first) { // First response is the hold count.
227                     this.holdsCount = Number(holdData);
228                     first = false;
229
230                 } else { // Subsequent responses are hold data blobs
231
232                     this.progressDialog.update(
233                         {value: ++loadCount, max: this.holdsCount});
234
235                     observer.next(holdData);
236                 }
237             },
238             err => {
239                 this.progressDialog.close();
240                 observer.error(err);
241             },
242             ()  => {
243                 this.progressDialog.close();
244                 observer.complete();
245             }
246         );
247
248         return observable;
249     }
250
251     showDetails(rows: any[]) {
252         this.showDetail(rows[0]);
253     }
254
255     showDetail(row: any) {
256         if (row) {
257             this.mode = 'detail';
258             this.detailHold = row;
259         }
260     }
261
262     showManager(rows: any[]) {
263         if (rows.length) {
264             this.mode = 'manage';
265             this.editHolds = rows.map(r => r.id);
266         }
267     }
268
269     handleModify(rowsModified: boolean) {
270         this.mode = 'list';
271
272         if (rowsModified) {
273             // give the grid a chance to render then ask it to reload
274             setTimeout(() => this.holdsGrid.reload());
275         }
276     }
277
278
279
280     showRecentCircs(rows: any[]) {
281         if (rows.length) {
282             const url =
283                 '/eg/staff/cat/item/' + rows[0].cp_id + '/circ_list';
284             window.open(url, '_blank');
285         }
286     }
287
288     showPatron(rows: any[]) {
289         if (rows.length) {
290             const url =
291                 '/eg/staff/circ/patron/' + rows[0].usr_id + '/checkout';
292             window.open(url, '_blank');
293         }
294     }
295
296     showManageDialog(rows: any[]) {
297         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
298         if (holdIds.length > 0) {
299             this.manageDialog.holdIds = holdIds;
300             this.manageDialog.open({size: 'lg'}).then(
301                 rowsModified => {
302                     if (rowsModified) {
303                         this.holdsGrid.reload();
304                     }
305                 },
306                 dismissed => {}
307             );
308         }
309     }
310
311     showTransferDialog(rows: any[]) {
312         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
313         if (holdIds.length > 0) {
314             this.transferDialog.holdIds = holdIds;
315             this.transferDialog.open({}).then(
316                 rowsModified => {
317                     if (rowsModified) {
318                         this.holdsGrid.reload();
319                     }
320                 },
321                 dismissed => {}
322             );
323         }
324     }
325
326     async showMarkDamagedDialog(rows: any[]) {
327         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
328         if (copyIds.length === 0) { return; }
329
330         let rowsModified = false;
331
332         const markNext = async(ids: number[]) => {
333             if (ids.length === 0) {
334                 return Promise.resolve();
335             }
336
337             this.markDamagedDialog.copyId = ids.pop();
338             this.markDamagedDialog.open({size: 'lg'}).then(
339                 ok => {
340                     if (ok) { rowsModified = true; }
341                     return markNext(ids);
342                 },
343                 dismiss => markNext(ids)
344             );
345         };
346
347         await markNext(copyIds);
348         if (rowsModified) {
349             this.holdsGrid.reload();
350         }
351     }
352
353     showMarkMissingDialog(rows: any[]) {
354         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
355         if (copyIds.length > 0) {
356             this.markMissingDialog.copyIds = copyIds;
357             this.markMissingDialog.open({}).then(
358                 rowsModified => {
359                     if (rowsModified) {
360                         this.holdsGrid.reload();
361                     }
362                 },
363                 dismissed => {} // avoid console errors
364             );
365         }
366     }
367
368     showRetargetDialog(rows: any[]) {
369         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
370         if (holdIds.length > 0) {
371             this.retargetDialog.holdIds = holdIds;
372             this.retargetDialog.open({}).then(
373                 rowsModified => {
374                     if (rowsModified) {
375                         this.holdsGrid.reload();
376                     }
377                 },
378                 dismissed => {}
379             );
380         }
381     }
382
383     showCancelDialog(rows: any[]) {
384         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
385         if (holdIds.length > 0) {
386             this.cancelDialog.holdIds = holdIds;
387             this.cancelDialog.open({}).then(
388                 rowsModified => {
389                     if (rowsModified) {
390                         this.holdsGrid.reload();
391                     }
392                 },
393                 dismissed => {}
394             );
395         }
396     }
397 }
398
399