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