]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/share/holds/grid.component.ts
LP1958265 Angular Holds Grids Not Printing Barcode
[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 {MarkDiscardDialogComponent
17     } from '@eg/staff/share/holdings/mark-discard-dialog.component';
18 import {HoldRetargetDialogComponent
19     } from '@eg/staff/share/holds/retarget-dialog.component';
20 import {HoldTransferDialogComponent} from './transfer-dialog.component';
21 import {HoldCancelDialogComponent} from './cancel-dialog.component';
22 import {HoldManageDialogComponent} from './manage-dialog.component';
23 import {PrintService} from '@eg/share/print/print.service';
24 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
25
26 /** Holds grid with access to detail page and other actions */
27
28 @Component({
29   selector: 'eg-holds-grid',
30   templateUrl: 'grid.component.html'
31 })
32 export class HoldsGridComponent implements OnInit {
33
34     // If either are set/true, the pickup lib selector will display
35     @Input() initialPickupLib: number | IdlObject;
36     @Input() hidePickupLibFilter: boolean;
37
38     // Setting a value here puts us into "pull list" mode.
39     @Input() pullListOrg: number;
40
41     // If true, only retrieve holds with a Hopeless Date
42     // and enable related Actions
43     @Input() hopeless: boolean;
44
45     // Grid persist key
46     @Input() persistKey: string;
47
48     @Input() preFetchSetting: string;
49
50     @Input() printTemplate: string;
51
52     // If set, all holds are fetched on grid load and sorting/paging all
53     // happens in the client.  If false, sorting and paging occur on
54     // the server.
55     @Input() enablePreFetch: boolean;
56
57     // How to sort when no sort parameters have been applied
58     // via grid controls.  This uses the eg-grid sort format:
59     // [{name: fname, dir: 'asc'}, {name: fname2, dir: 'desc'}]
60     @Input() defaultSort: any[];
61
62     // To pass through to the underlying eg-grid
63     @Input() showFields: string;
64
65     // Display bib record summary along the top of the detail page.
66     @Input() showRecordSummary = false;
67
68     mode: 'list' | 'detail' | 'manage' = 'list';
69     initDone = false;
70     holdsCount: number;
71     pickupLib: IdlObject;
72     plCompLoaded = false;
73     gridDataSource: GridDataSource;
74     detailHold: any;
75     editHolds: number[];
76     transferTarget: number;
77
78     @ViewChild('holdsGrid', { static: false }) private holdsGrid: GridComponent;
79     @ViewChild('progressDialog', { static: true })
80         private progressDialog: ProgressDialogComponent;
81     @ViewChild('transferDialog', { static: true })
82         private transferDialog: HoldTransferDialogComponent;
83     @ViewChild('markDamagedDialog', { static: true })
84         private markDamagedDialog: MarkDamagedDialogComponent;
85     @ViewChild('markMissingDialog', { static: true })
86         private markMissingDialog: MarkMissingDialogComponent;
87     @ViewChild('markDiscardDialog')
88         private markDiscardDialog: MarkDiscardDialogComponent;
89     @ViewChild('retargetDialog', { static: true })
90         private retargetDialog: HoldRetargetDialogComponent;
91     @ViewChild('cancelDialog', { static: true })
92         private cancelDialog: HoldCancelDialogComponent;
93     @ViewChild('manageDialog', { static: true })
94         private manageDialog: HoldManageDialogComponent;
95
96     // Bib record ID.
97     _recordId: number;
98     @Input() set recordId(id: number) {
99         this._recordId = id;
100         if (this.initDone) { // reload on update
101             this.holdsGrid.reload();
102         }
103     }
104
105     _userId: number;
106     @Input() set userId(id: number) {
107         this._userId = id;
108         if (this.initDone) {
109             this.holdsGrid.reload();
110         }
111     }
112
113     // Include holds canceled on or after the provided date.
114     // If no value is passed, canceled holds are not displayed.
115     _showCanceledSince: Date;
116     @Input() set showCanceledSince(show: Date) {
117         this._showCanceledSince = show;
118         if (this.initDone) { // reload on update
119             this.holdsGrid.reload();
120         }
121     }
122
123     // Include holds fulfilled on or after hte provided date.
124     // If no value is passed, fulfilled holds are not displayed.
125     _showFulfilledSince: Date;
126     @Input() set showFulfilledSince(show: Date) {
127         this._showFulfilledSince = show;
128         if (this.initDone) { // reload on update
129             this.holdsGrid.reload();
130         }
131     }
132
133
134     cellTextGenerator: GridCellTextGenerator;
135
136     // Include holds marked Hopeless on or after this date.
137     _showHopelessAfter: Date;
138     @Input() set showHopelessAfter(show: Date) {
139         this._showHopelessAfter = show;
140         if (this.initDone) { // reload on update
141             this.holdsGrid.reload();
142         }
143     }
144
145     // Include holds marked Hopeless on or before this date.
146     _showHopelessBefore: Date;
147     @Input() set showHopelessBefore(show: Date) {
148         this._showHopelessBefore = show;
149         if (this.initDone) { // reload on update
150             this.holdsGrid.reload();
151         }
152     }
153
154     constructor(
155         private net: NetService,
156         private org: OrgService,
157         private store: ServerStoreService,
158         private auth: AuthService,
159         private printer: PrintService,
160         private holdings: HoldingsService
161     ) {
162         this.gridDataSource = new GridDataSource();
163         this.enablePreFetch = null;
164     }
165
166     ngOnInit() {
167         this.initDone = true;
168         this.pickupLib = this.org.get(this.initialPickupLib);
169
170         if (this.preFetchSetting) {
171             this.store.getItem(this.preFetchSetting).then(
172                 applied => this.enablePreFetch = Boolean(applied)
173             );
174         }
175
176         if (!this.defaultSort) {
177             if (this.pullListOrg) {
178
179                 this.defaultSort = [
180                     {name: 'copy_location_order_position', dir: 'asc'},
181                     {name: 'acpl_name', dir: 'asc'},
182                     {name: 'ancp_label', dir: 'asc'}, // NOTE: API typo "ancp"
183                     {name: 'cn_label_sortkey', dir: 'asc'},
184                     {name: 'ancs_label', dir: 'asc'} // NOTE: API typo "ancs"
185                 ];
186
187             } else {
188                 this.defaultSort = [{name: 'request_time', dir: 'asc'}];
189             }
190         }
191
192         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
193
194             if (!this.hidePickupLibFilter && !this.plCompLoaded) {
195                 // When the pickup lib selector is active, avoid any
196                 // data fetches until it has settled on a default value.
197                 // Once the final value is applied, its onchange will
198                 // fire and we'll be back here with plCompLoaded=true.
199                 return of([]);
200             }
201
202             sort = sort.length > 0 ? sort : this.defaultSort;
203             return this.fetchHolds(pager, sort);
204         };
205
206         // Text-ify function for cells that use display templates.
207         this.cellTextGenerator = {
208             title: row => row.title,
209             cp_barcode: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
210             current_item: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
211             requested_item: row => (row.cp_barcode == null) ? '' : row.cp_barcode,
212             ucard_barcode: row => row.ucard_barcode
213         };
214     }
215
216     // Returns true after all data/settings/etc required to render the
217     // grid have been fetched.
218     initComplete(): boolean {
219         return this.enablePreFetch !== null;
220     }
221
222     pickupLibChanged(org: IdlObject) {
223         this.pickupLib = org;
224         this.holdsGrid.reload();
225     }
226
227     pullListOrgChanged(org: IdlObject) {
228         this.pullListOrg = org.id();
229         this.holdsGrid.reload();
230     }
231
232     preFetchHolds(apply: boolean) {
233         this.enablePreFetch = apply;
234
235         if (apply) {
236             setTimeout(() => this.holdsGrid.reload());
237         }
238
239         if (this.preFetchSetting) {
240             // fire and forget
241             this.store.setItem(this.preFetchSetting, apply);
242         }
243     }
244
245     applyFilters(): any {
246
247         const filters: any = {};
248
249         if (this.pullListOrg) {
250             filters.cancel_time = null;
251             filters.capture_time = null;
252             filters.frozen = 'f';
253
254             // cp.* fields are set for copy-level holds even if they
255             // have no current_copy.  Make sure current_copy is set.
256             filters.current_copy = {'is not': null};
257
258             // There are aliases for these (cp_status, cp_circ_lib),
259             // but the API complains when I use them.
260             filters['cp.status'] = [0, 7];
261             filters['cp.circ_lib'] = this.pullListOrg;
262
263             return filters;
264         }
265
266         if (this._showFulfilledSince) {
267             filters.fulfillment_time = this._showFulfilledSince.toISOString();
268         } else {
269             filters.fulfillment_time = null;
270         }
271
272         if (this._showCanceledSince) {
273             filters.cancel_time = this._showCanceledSince.toISOString();
274         } else {
275             filters.cancel_time = null;
276         }
277
278         if (this.hopeless) {
279           filters['hopeless_holds'] = {
280             'start_date' : this._showHopelessAfter
281               ? (
282                   // FIXME -- consistency desired, string or object
283                   typeof this._showHopelessAfter === 'object'
284                   ? this._showHopelessAfter.toISOString()
285                   : this._showHopelessAfter
286                 )
287               : '1970-01-01T00:00:00.000Z',
288             'end_date' : this._showHopelessBefore
289               ? (
290                   // FIXME -- consistency desired, string or object
291                   typeof this._showHopelessBefore === 'object'
292                   ? this._showHopelessBefore.toISOString()
293                   : this._showHopelessBefore
294                 )
295               : (new Date()).toISOString()
296           };
297         }
298
299         if (this.pickupLib) {
300             filters.pickup_lib =
301                 this.org.descendants(this.pickupLib, true);
302         }
303
304         if (this._recordId) {
305             filters.record_id = this._recordId;
306         }
307
308         if (this._userId) {
309             filters.usr_id = this._userId;
310         }
311
312         return filters;
313     }
314
315     fetchHolds(pager: Pager, sort: any[]): Observable<any> {
316
317         // We need at least one filter.
318         if (!this._recordId && !this.pickupLib && !this._userId && !this.pullListOrg) {
319             return of([]);
320         }
321
322         const filters = this.applyFilters();
323
324         const orderBy: any = [];
325         if (sort.length > 0) {
326             sort.forEach(obj => {
327                 const subObj: any = {};
328                 subObj[obj.name] = {dir: obj.dir, nulls: 'last'};
329                 orderBy.push(subObj);
330             });
331         }
332
333         const limit = this.enablePreFetch ? null : pager.limit;
334         const offset = this.enablePreFetch ? 0 : pager.offset;
335
336         let observer: Observer<any>;
337         const observable = new Observable(obs => observer = obs);
338
339         this.progressDialog.open();
340         this.progressDialog.update({value: 0, max: 1});
341         let first = true;
342         let loadCount = 0;
343         this.net.request(
344             'open-ils.circ',
345             'open-ils.circ.hold.wide_hash.stream',
346             this.auth.token(), filters, orderBy, limit, offset
347         ).subscribe(
348             holdData => {
349
350                 if (first) { // First response is the hold count.
351                     this.holdsCount = Number(holdData);
352                     first = false;
353
354                 } else { // Subsequent responses are hold data blobs
355
356                     this.progressDialog.update(
357                         {value: ++loadCount, max: this.holdsCount});
358
359                     observer.next(holdData);
360                 }
361             },
362             err => {
363                 this.progressDialog.close();
364                 observer.error(err);
365             },
366             ()  => {
367                 this.progressDialog.close();
368                 observer.complete();
369             }
370         );
371
372         return observable;
373     }
374
375     metaRecordHoldsSelected(rows: IdlObject[]) {
376         let found = false;
377         rows.forEach( row => {
378            if (row.hold_type === 'M') {
379              found = true;
380            }
381         });
382         return found;
383     }
384
385     nonTitleHoldsSelected(rows: IdlObject[]) {
386         let found = false;
387         rows.forEach( row => {
388            if (row.hold_type !== 'T') {
389              found = true;
390            }
391         });
392         return found;
393     }
394
395     showDetails(rows: any[]) {
396         this.showDetail(rows[0]);
397     }
398
399     showDetail(row: any) {
400         if (row) {
401             this.mode = 'detail';
402             this.detailHold = row;
403         }
404     }
405
406     showManager(rows: any[]) {
407         if (rows.length) {
408             this.mode = 'manage';
409             this.editHolds = rows.map(r => r.id);
410         }
411     }
412
413     handleModify(rowsModified: boolean) {
414         this.mode = 'list';
415
416         if (rowsModified) {
417             // give the grid a chance to render then ask it to reload
418             setTimeout(() => this.holdsGrid.reload());
419         }
420     }
421
422
423
424     showRecentCircs(rows: any[]) {
425         const copyIds = Array.from(new Set( rows.map(r => r.cp_id).filter( cp_id => Boolean(cp_id)) ));
426         copyIds.forEach( copyId => {
427             const url =
428                 '/eg/staff/cat/item/' + copyId + '/circ_list';
429             window.open(url, '_blank');
430         });
431     }
432
433     showPatron(rows: any[]) {
434         const usrIds = Array.from(new Set( rows.map(r => r.usr_id).filter( usr_id => Boolean(usr_id)) ));
435         usrIds.forEach( usrId => {
436             const url =
437                 '/eg/staff/circ/patron/' + usrId + '/checkout';
438             window.open(url, '_blank');
439         });
440     }
441
442     showOrder(rows: any[]) {
443         // Doesn't work in Typescript currently without compiler option:
444         //   const bibIds = [...new Set( rows.map(r => r.record_id) )];
445         const bibIds = Array.from(
446           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
447         bibIds.forEach( bibId => {
448           const url =
449               '/eg/staff/acq/legacy/lineitem/related/' + bibId + '?target=bib';
450           window.open(url, '_blank');
451         });
452     }
453
454     addVolume(rows: any[]) {
455         const bibIds = Array.from(
456           new Set( rows.filter(r => r.hold_type !== 'M').map(r => r.record_id) ));
457         bibIds.forEach( bibId => {
458           this.holdings.spawnAddHoldingsUi(bibId);
459         });
460     }
461
462     showTitle(rows: any[]) {
463         const bibIds = Array.from(new Set( rows.map(r => r.record_id) ));
464         bibIds.forEach( bibId => {
465           // const url = '/eg/staff/cat/catalog/record/' + bibId;
466           const url = '/eg2/staff/catalog/record/' + bibId;
467           window.open(url, '_blank');
468         });
469     }
470
471     showManageDialog(rows: any[]) {
472         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
473         if (holdIds.length > 0) {
474             this.manageDialog.holdIds = holdIds;
475             this.manageDialog.open({size: 'lg'}).subscribe(
476                 rowsModified => {
477                     if (rowsModified) {
478                         this.holdsGrid.reload();
479                     }
480                 }
481             );
482         }
483     }
484
485     showTransferDialog(rows: any[]) {
486         const holdIds = rows.filter(r => r.hold_type === 'T').map(r => r.id).filter(id => Boolean(id));
487         if (holdIds.length > 0) {
488             this.transferDialog.holdIds = holdIds;
489             this.transferDialog.open({}).subscribe(
490                 rowsModified => {
491                     if (rowsModified) {
492                         this.holdsGrid.reload();
493                     }
494                 }
495             );
496         }
497     }
498
499     async showMarkDamagedDialog(rows: any[]) {
500         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
501         if (copyIds.length === 0) { return; }
502
503         let rowsModified = false;
504
505         const markNext = async(ids: number[]) => {
506             if (ids.length === 0) {
507                 return Promise.resolve();
508             }
509
510             this.markDamagedDialog.copyId = ids.pop();
511             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
512                 ok => {
513                     if (ok) { rowsModified = true; }
514                     return markNext(ids);
515                 },
516                 dismiss => markNext(ids)
517             );
518         };
519
520         await markNext(copyIds);
521         if (rowsModified) {
522             this.holdsGrid.reload();
523         }
524     }
525
526     showMarkMissingDialog(rows: any[]) {
527         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
528         if (copyIds.length > 0) {
529             this.markMissingDialog.copyIds = copyIds;
530             this.markMissingDialog.open({}).subscribe(
531                 rowsModified => {
532                     if (rowsModified) {
533                         this.holdsGrid.reload();
534                     }
535                 }
536             );
537         }
538     }
539
540     showMarkDiscardDialog(rows: any[]) {
541         const copyIds = rows.map(r => r.cp_id).filter(id => Boolean(id));
542         if (copyIds.length > 0) {
543             this.markDiscardDialog.copyIds = copyIds;
544             this.markDiscardDialog.open({}).subscribe(
545                 rowsModified => {
546                     if (rowsModified) {
547                         this.holdsGrid.reload();
548                     }
549                 }
550             );
551         }
552     }
553
554
555     showRetargetDialog(rows: any[]) {
556         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
557         if (holdIds.length > 0) {
558             this.retargetDialog.holdIds = holdIds;
559             this.retargetDialog.open({}).subscribe(
560                 rowsModified => {
561                     if (rowsModified) {
562                         this.holdsGrid.reload();
563                     }
564                 }
565             );
566         }
567     }
568
569     showCancelDialog(rows: any[]) {
570         const holdIds = rows.map(r => r.id).filter(id => Boolean(id));
571         if (holdIds.length > 0) {
572             this.cancelDialog.holdIds = holdIds;
573             this.cancelDialog.open({}).subscribe(
574                 rowsModified => {
575                     if (rowsModified) {
576                         this.holdsGrid.reload();
577                     }
578                 }
579             );
580         }
581     }
582
583     printHolds() {
584         // Request a page with no limit to get all of the wide holds for
585         // printing.  Call requestPage() directly instead of grid.reload()
586         // since we may already have the data.
587
588         const pager = new Pager();
589         pager.offset = 0;
590         pager.limit = null;
591
592         if (this.gridDataSource.sort.length === 0) {
593             this.gridDataSource.sort = this.defaultSort;
594         }
595
596         this.gridDataSource.requestPage(pager).then(() => {
597             if (this.gridDataSource.data.length > 0) {
598                 this.printer.print({
599                     templateName: this.printTemplate || 'holds_for_bib',
600                     contextData: this.gridDataSource.data,
601                     printContext: 'default'
602                 });
603             }
604         });
605     }
606
607     isCopyHold(holdData: any): boolean {
608         return holdData.hold_type.match(/C|R|F/) !== null;
609     }
610 }
611
612
613
614