]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
lp1811710: toward hopeless UI
[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     showDetails(rows: any[]) {
334         this.showDetail(rows[0]);
335     }
336
337     showDetail(row: any) {
338         if (row) {
339             this.mode = 'detail';
340             this.detailHold = row;
341         }
342     }
343
344     showManager(rows: any[]) {
345         if (rows.length) {
346             this.mode = 'manage';
347             this.editHolds = rows.map(r => r.id);
348         }
349     }
350
351     handleModify(rowsModified: boolean) {
352         this.mode = 'list';
353
354         if (rowsModified) {
355             // give the grid a chance to render then ask it to reload
356             setTimeout(() => this.holdsGrid.reload());
357         }
358     }
359
360
361
362     showRecentCircs(rows: any[]) {
363         if (rows.length) {
364             const url =
365                 '/eg/staff/cat/item/' + rows[0].cp_id + '/circ_list';
366             window.open(url, '_blank');
367         }
368     }
369
370     showPatron(rows: any[]) {
371         if (rows.length) {
372             const url =
373                 '/eg/staff/circ/patron/' + rows[0].usr_id + '/checkout';
374             window.open(url, '_blank');
375         }
376     }
377
378     showOrder(rows: any[]) {
379         //Doesn't work in Typescript currently without compiler option:
380         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
381         const bibIds = Array.from(
382           new Set( rows.filter(r => r.hold_type!='M').map(r => r.record_id) ));
383         bibIds.forEach( bibId => {
384           const url =
385               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
386           window.open(url, '_blank');
387         });
388     }
389
390     addVolume(rows: any[]) {
391         const bibIds = Array.from(
392           new Set( rows.filter(r => r.hold_type!='M').map(r => r.record_id) ));
393         bibIds.forEach( bibId => {
394           this.holdings.spawnAddHoldingsUi(bibId);
395         });
396     }
397
398     showTitle(rows: any[]) {
399         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
400         bibIds.forEach( bibId => {
401           //const url = '/eg/staff/cat/catalog/record/' + bibId;
402           const url = '/eg2/staff/catalog/record/' + bibId;
403           window.open(url, '_blank');
404         });
405     }
406
407     showManageDialog(rows: any[]) {
408         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
409         if (holdIds.length > 0) {
410             this.manageDialog.holdIds = holdIds;
411             this.manageDialog.open({size: 'lg'}).subscribe(
412                 rowsModified => {
413                     if (rowsModified) {
414                         this.holdsGrid.reload();
415                     }
416                 }
417             );
418         }
419     }
420
421     showTransferDialog(rows: any[]) {
422         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
423         if (holdIds.length > 0) {
424             this.transferDialog.holdIds = holdIds;
425             this.transferDialog.open({}).subscribe(
426                 rowsModified => {
427                     if (rowsModified) {
428                         this.holdsGrid.reload();
429                     }
430                 }
431             );
432         }
433     }
434
435     async showMarkDamagedDialog(rows: any[]) {
436         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
437         if (copyIds.length === 0) { return; }
438
439         let rowsModified = false;
440
441         const markNext = async(ids: number[]) => {
442             if (ids.length === 0) {
443                 return Promise.resolve();
444             }
445
446             this.markDamagedDialog.copyId = ids.pop();
447             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
448                 ok => {
449                     if (ok) { rowsModified = true; }
450                     return markNext(ids);
451                 },
452                 dismiss => markNext(ids)
453             );
454         };
455
456         await markNext(copyIds);
457         if (rowsModified) {
458             this.holdsGrid.reload();
459         }
460     }
461
462     showMarkMissingDialog(rows: any[]) {
463         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
464         if (copyIds.length > 0) {
465             this.markMissingDialog.copyIds = copyIds;
466             this.markMissingDialog.open({}).subscribe(
467                 rowsModified => {
468                     if (rowsModified) {
469                         this.holdsGrid.reload();
470                     }
471                 }
472             );
473         }
474     }
475
476     showRetargetDialog(rows: any[]) {
477         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
478         if (holdIds.length > 0) {
479             this.retargetDialog.holdIds = holdIds;
480             this.retargetDialog.open({}).subscribe(
481                 rowsModified => {
482                     if (rowsModified) {
483                         this.holdsGrid.reload();
484                     }
485                 }
486             );
487         }
488     }
489
490     showCancelDialog(rows: any[]) {
491         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
492         if (holdIds.length > 0) {
493             this.cancelDialog.holdIds = holdIds;
494             this.cancelDialog.open({}).subscribe(
495                 rowsModified => {
496                     if (rowsModified) {
497                         this.holdsGrid.reload();
498                     }
499                 }
500             );
501         }
502     }
503
504     printHolds() {
505         // Request a page with no limit to get all of the wide holds for
506         // printing.  Call requestPage() directly instead of grid.reload()
507         // since we may already have the data.
508
509         const pager = new Pager();
510         pager.offset = 0;
511         pager.limit = null;
512
513         if (this.gridDataSource.sort.length === 0) {
514             this.gridDataSource.sort = this.defaultSort;
515         }
516
517         this.gridDataSource.requestPage(pager).then(() => {
518             if (this.gridDataSource.data.length > 0) {
519                 this.printer.print({
520                     templateName: this.printTemplate || 'holds_for_bib',
521                     contextData: this.gridDataSource.data,
522                     printContext: 'default'
523                 });
524             }
525         });
526     }
527 }
528
529
530
531