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