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