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