]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/catalog/record/holdings.component.ts
LP1888723 Angular Holdings Maintenance / Item Attributes Editor
[Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / catalog / record / holdings.component.ts
1 import {Component, OnInit, Input, ViewChild, ViewEncapsulation
2     } from '@angular/core';
3 import {Router} from '@angular/router';
4 import {Observable, Observer, of, empty} from 'rxjs';
5 import {map} from 'rxjs/operators';
6 import {Pager} from '@eg/share/util/pager';
7 import {IdlObject, IdlService} from '@eg/core/idl.service';
8 import {StaffCatalogService} from '../catalog.service';
9 import {OrgService} from '@eg/core/org.service';
10 import {PcrudService} from '@eg/core/pcrud.service';
11 import {AuthService} from '@eg/core/auth.service';
12 import {GridDataSource, GridColumn, GridCellTextGenerator} from '@eg/share/grid/grid';
13 import {GridComponent} from '@eg/share/grid/grid.component';
14 import {GridToolbarCheckboxComponent
15     } from '@eg/share/grid/grid-toolbar-checkbox.component';
16 import {StoreService} from '@eg/core/store.service';
17 import {ServerStoreService} from '@eg/core/server-store.service';
18 import {MarkDamagedDialogComponent
19     } from '@eg/staff/share/holdings/mark-damaged-dialog.component';
20 import {MarkMissingDialogComponent
21     } from '@eg/staff/share/holdings/mark-missing-dialog.component';
22 import {AnonCacheService} from '@eg/share/util/anon-cache.service';
23 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
24 import {CopyAlertsDialogComponent
25     } from '@eg/staff/share/holdings/copy-alerts-dialog.component';
26 import {CopyTagsDialogComponent
27     } from '@eg/staff/share/holdings/copy-tags-dialog.component';
28 import {ReplaceBarcodeDialogComponent
29     } from '@eg/staff/share/holdings/replace-barcode-dialog.component';
30 import {DeleteHoldingDialogComponent
31     } from '@eg/staff/share/holdings/delete-volcopy-dialog.component';
32 import {BucketDialogComponent
33     } from '@eg/staff/share/buckets/bucket-dialog.component';
34 import {ConjoinedItemsDialogComponent
35     } from '@eg/staff/share/holdings/conjoined-items-dialog.component';
36 import {MakeBookableDialogComponent
37     } from '@eg/staff/share/booking/make-bookable-dialog.component';
38 import {TransferItemsComponent
39     } from '@eg/staff/share/holdings/transfer-items.component';
40 import {TransferHoldingsComponent
41     } from '@eg/staff/share/holdings/transfer-holdings.component';
42 import {AlertDialogComponent} from '@eg/share/dialog/alert.component';
43 import {BroadcastService} from '@eg/share/util/broadcast.service';
44
45
46 // The holdings grid models a single HoldingsTree, composed of HoldingsTreeNodes
47 // flattened on-demand into a list of HoldingEntry objects.
48 export class HoldingsTreeNode {
49     children: HoldingsTreeNode[];
50     nodeType: 'org' | 'callNum' | 'copy';
51     target: any;
52     parentNode: HoldingsTreeNode;
53     expanded: boolean;
54     copyCount: number;
55     callNumCount: number;
56     constructor() {
57         this.children = [];
58     }
59 }
60
61 class HoldingsTree {
62     root: HoldingsTreeNode;
63     constructor() {
64         this.root = new HoldingsTreeNode();
65     }
66 }
67
68 export class HoldingsEntry {
69     index: number;
70     // org unit shortname, call number label, or copy barcode
71     locationLabel: string;
72     // location label indentation depth
73     locationDepth: number | null;
74     callNumCount: number | null;
75     copyCount: number | null;
76     callNumberLabel: string;
77     copy: IdlObject;
78     callNum: IdlObject;
79     circ: IdlObject;
80     treeNode: HoldingsTreeNode;
81 }
82
83 @Component({
84   selector: 'eg-holdings-maintenance',
85   templateUrl: 'holdings.component.html',
86   styleUrls: ['holdings.component.css'],
87   encapsulation: ViewEncapsulation.None
88 })
89 export class HoldingsMaintenanceComponent implements OnInit {
90
91     initDone = false;
92     gridDataSource: GridDataSource;
93     gridTemplateContext: any;
94     @ViewChild('holdingsGrid', { static: true }) holdingsGrid: GridComponent;
95
96     // Manage visibility of various sub-sections
97     @ViewChild('callNumsCheckbox', { static: true })
98         private callNumsCheckbox: GridToolbarCheckboxComponent;
99     @ViewChild('copiesCheckbox', { static: true })
100         private copiesCheckbox: GridToolbarCheckboxComponent;
101     @ViewChild('emptyCallNumsCheckbox', { static: true })
102         private emptyCallNumsCheckbox: GridToolbarCheckboxComponent;
103     @ViewChild('emptyLibsCheckbox', { static: true })
104         private emptyLibsCheckbox: GridToolbarCheckboxComponent;
105     @ViewChild('markDamagedDialog', { static: true })
106         private markDamagedDialog: MarkDamagedDialogComponent;
107     @ViewChild('markMissingDialog', { static: true })
108         private markMissingDialog: MarkMissingDialogComponent;
109     @ViewChild('copyAlertsDialog', { static: true })
110         private copyAlertsDialog: CopyAlertsDialogComponent;
111     @ViewChild('copyTagsDialog', {static: false})
112         private copyTagsDialog: CopyTagsDialogComponent;
113     @ViewChild('replaceBarcode', { static: true })
114         private replaceBarcode: ReplaceBarcodeDialogComponent;
115     @ViewChild('deleteHolding', { static: true })
116         private deleteHolding: DeleteHoldingDialogComponent;
117     @ViewChild('bucketDialog', { static: true })
118         private bucketDialog: BucketDialogComponent;
119     @ViewChild('conjoinedDialog', { static: true })
120         private conjoinedDialog: ConjoinedItemsDialogComponent;
121     @ViewChild('makeBookableDialog', { static: true })
122         private makeBookableDialog: MakeBookableDialogComponent;
123     @ViewChild('transferItems', {static: false})
124         private transferItems: TransferItemsComponent;
125     @ViewChild('transferHoldings', {static: false})
126         private transferHoldings: TransferHoldingsComponent;
127     @ViewChild('transferAlert', {static: false})
128         private transferAlert: AlertDialogComponent;
129
130     holdingsTree: HoldingsTree;
131
132     // nodeType => id => tree node cache
133     treeNodeCache: {[nodeType: string]: {[id: number]: HoldingsTreeNode}};
134
135     // When true and a grid reload is called, the holdings data will be
136     // re-fetched from the server.
137     refreshHoldings: boolean;
138
139     // Used as a row identifier in th grid, since we're mixing object types.
140     gridIndex: number;
141
142     // List of copies whose due date we need to retrieve.
143     itemCircsNeeded: IdlObject[];
144
145     // When true draw the grid based on the stored preferences.
146     // When not true, render based on the current "expanded" state of each node.
147     // Rendering from prefs happens on initial load and when any prefs change.
148     renderFromPrefs: boolean;
149
150     rowClassCallback: (row: any) => string;
151     cellTextGenerator: GridCellTextGenerator;
152
153     private _recId: number;
154     @Input() set recordId(id: number) {
155         this._recId = id;
156         // Only force new data collection when recordId()
157         // is invoked after ngInit() has already run.
158         if (this.initDone) {
159             this.hardRefresh();
160         }
161     }
162     get recordId(): number {
163         return this._recId;
164     }
165
166     contextOrg: IdlObject;
167
168     // The context org may come from a workstation setting.
169     // Wait for confirmation from the org-select (via onchange in this
170     // case) that the desired context org unit has been found.
171     contextOrgLoaded = false;
172
173     constructor(
174         private router: Router,
175         private org: OrgService,
176         private idl: IdlService,
177         private pcrud: PcrudService,
178         private auth: AuthService,
179         private staffCat: StaffCatalogService,
180         private store: ServerStoreService,
181         private localStore: StoreService,
182         private holdings: HoldingsService,
183         private broadcaster: BroadcastService,
184         private anonCache: AnonCacheService
185     ) {
186         // Set some sane defaults before settings are loaded.
187         this.gridDataSource = new GridDataSource();
188         this.refreshHoldings = true;
189         this.renderFromPrefs = true;
190
191         // TODO: need a separate setting for this?
192         this.contextOrg = this.staffCat.searchContext.searchOrg;
193
194         this.rowClassCallback = (row: any): string => {
195             if (row.callNum) {
196                 if (row.copy) {
197                     return 'holdings-copy-row';
198                 } else {
199                     return 'holdings-callNum-row';
200                 }
201             } else {
202                 // Add a generic org unit class and a depth-specific
203                 // class for styling different levels of the org tree.
204                 return 'holdings-org-row holdings-org-row-' +
205                     row.treeNode.target.ou_type().depth();
206             }
207         };
208
209         // Text-ify function for cells that use display templates.
210         this.cellTextGenerator = {
211             owner_label: row => row.locationLabel,
212             holdable: row => row.copy ?
213                 this.gridTemplateContext.copyIsHoldable(row.copy) : ''
214         };
215
216         this.gridTemplateContext = {
217             toggleExpandRow: (row: HoldingsEntry) => {
218                 row.treeNode.expanded = !row.treeNode.expanded;
219
220                 if (!row.treeNode.expanded) {
221                     // When collapsing a node, all child nodes should be
222                     // collapsed as well.
223                     const traverse = (node: HoldingsTreeNode) => {
224                         node.expanded = false;
225                         node.children.forEach(traverse);
226                     };
227                     traverse(row.treeNode);
228                 }
229
230                 this.holdingsGrid.reload();
231             },
232
233             copyIsHoldable: (copy: IdlObject): boolean => {
234                 return copy.holdable() === 't'
235                     && copy.location().holdable() === 't'
236                     && copy.status().holdable() === 't';
237             }
238         };
239     }
240
241     ngOnInit() {
242         this.initDone = true;
243
244         this.broadcaster.listen('eg.holdings.update').subscribe(data => {
245             if (data && data.records && data.records.includes(this.recordId)) {
246                 this.refreshHoldings = true;
247                 this.holdingsGrid.reload();
248             }
249         });
250
251         // These are pre-cached via the catalog resolver.
252         const settings = this.store.getItemBatchCached([
253             'cat.holdings_show_empty_org',
254             'cat.holdings_show_empty',
255             'cat.holdings_show_copies',
256             'cat.holdings_show_vols'
257         ]);
258
259         // Show call numbers by default when no preference is set.
260         let showCallNums = settings['cat.holdings_show_vols'];
261         if (showCallNums === null) { showCallNums = true; }
262
263         this.callNumsCheckbox.checked(showCallNums);
264         this.copiesCheckbox.checked(settings['cat.holdings_show_copies']);
265         this.emptyCallNumsCheckbox.checked(settings['cat.holdings_show_empty']);
266         this.emptyLibsCheckbox.checked(settings['cat.holdings_show_empty_org']);
267
268         this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
269             if (!this.contextOrgLoaded) { return empty(); }
270             return this.fetchHoldings(pager);
271         };
272     }
273
274     // No data is loaded until the first occurrence of the org change handler
275     contextOrgChanged(org: IdlObject) {
276         this.contextOrgLoaded = true;
277         this.contextOrg = org;
278         this.hardRefresh();
279     }
280
281     hardRefresh() {
282         this.renderFromPrefs = true;
283         this.refreshHoldings = true;
284         this.initHoldingsTree();
285         this.holdingsGrid.reload();
286     }
287
288     toggleShowCopies(value: boolean) {
289         this.store.setItem('cat.holdings_show_copies', value);
290         if (value) {
291             // Showing copies implies showing call numbers
292             this.callNumsCheckbox.checked(true);
293         }
294         this.renderFromPrefs = true;
295         this.holdingsGrid.reload();
296     }
297
298     toggleShowCallNums(value: boolean) {
299         this.store.setItem('cat.holdings_show_vols', value);
300         if (!value) {
301             // Hiding call numbers implies hiding empty call numbers and copies.
302             this.copiesCheckbox.checked(false);
303             this.emptyCallNumsCheckbox.checked(false);
304         }
305         this.renderFromPrefs = true;
306         this.holdingsGrid.reload();
307     }
308
309     toggleShowEmptyCallNums(value: boolean) {
310         this.store.setItem('cat.holdings_show_empty', value);
311         if (value) {
312             this.callNumsCheckbox.checked(true);
313         }
314         this.renderFromPrefs = true;
315         this.holdingsGrid.reload();
316     }
317
318     toggleShowEmptyLibs(value: boolean) {
319         this.store.setItem('cat.holdings_show_empty_org', value);
320         this.renderFromPrefs = true;
321         this.holdingsGrid.reload();
322     }
323
324     onRowActivate(row: any) {
325         if (row.copy) {
326             // Launch copy editor?
327         } else {
328             this.gridTemplateContext.toggleExpandRow(row);
329         }
330     }
331
332     initHoldingsTree() {
333
334         const visibleOrgs = this.org.fullPath(this.contextOrg, true);
335
336         // The initial tree simply matches the org unit tree
337         const traverseOrg = (node: HoldingsTreeNode) => {
338             node.target.children().forEach((org: IdlObject) => {
339                 if (visibleOrgs.indexOf(org.id()) === -1) {
340                     return; // Org is outside of scope
341                 }
342                 const nodeChild = new HoldingsTreeNode();
343                 nodeChild.nodeType = 'org';
344                 nodeChild.target = org;
345                 nodeChild.parentNode = node;
346                 node.children.push(nodeChild);
347                 this.treeNodeCache.org[org.id()] = nodeChild;
348                 traverseOrg(nodeChild);
349             });
350         };
351
352         this.treeNodeCache = {
353             org: {},
354             callNum: {},
355             copy: {}
356         };
357
358         this.holdingsTree = new HoldingsTree();
359         this.holdingsTree.root.nodeType = 'org';
360         this.holdingsTree.root.target = this.org.root();
361         this.treeNodeCache.org[this.org.root().id()] = this.holdingsTree.root;
362
363         traverseOrg(this.holdingsTree.root);
364     }
365
366     // Org node children are sorted with any child org nodes pushed to the
367     // front, followed by the call number nodes sorted alphabetcially by label.
368     sortOrgNodeChildren(node: HoldingsTreeNode) {
369         node.children = node.children.sort((a, b) => {
370             if (a.nodeType === 'org') {
371                 if (b.nodeType === 'org') {
372                     return a.target.shortname() < b.target.shortname() ? -1 : 1;
373                 } else {
374                     return -1;
375                 }
376             } else if (b.nodeType === 'org') {
377                 return 1;
378             } else {
379                 // TODO: should this use label sortkey instead of
380                 // the compiled call number label?
381                 return a.target._label < b.target._label ? -1 : 1;
382             }
383         });
384     }
385
386     // Sets call number and copy count sums to nodes that need it.
387     // Applies the initial expansed state of each container node.
388     setTreeCounts(node: HoldingsTreeNode) {
389
390         if (node.nodeType === 'org') {
391             node.copyCount = 0;
392             node.callNumCount = 0;
393         } else if (node.nodeType === 'callNum') {
394             node.copyCount = 0;
395         }
396
397         let hasChildOrgWithData = false;
398         let hasChildOrgSansData = false;
399         node.children.forEach(child => {
400             this.setTreeCounts(child);
401             if (node.nodeType === 'org') {
402                 node.copyCount += child.copyCount;
403                 if (child.nodeType === 'callNum') {
404                     node.callNumCount++;
405                 } else {
406                     hasChildOrgWithData = child.callNumCount > 0;
407                     hasChildOrgSansData = child.callNumCount === 0;
408                     node.callNumCount += child.callNumCount;
409                 }
410             } else if (node.nodeType === 'callNum') {
411                 node.copyCount = node.children.length;
412                 if (this.renderFromPrefs) {
413                     node.expanded = this.copiesCheckbox.checked();
414                 }
415             }
416         });
417
418         if (this.renderFromPrefs && node.nodeType === 'org') {
419             if (node.copyCount > 0 && this.callNumsCheckbox.checked()) {
420                 node.expanded = true;
421             } else if (node.callNumCount > 0 && this.emptyCallNumsCheckbox.checked()) {
422                 node.expanded = true;
423             } else if (hasChildOrgWithData) {
424                 node.expanded = true;
425             } else if (hasChildOrgSansData && this.emptyLibsCheckbox.checked()) {
426                 node.expanded = true;
427             } else {
428                 node.expanded = false;
429             }
430         }
431     }
432
433     // Create HoldingsEntry objects for tree nodes that should be displayed
434     // and relays them to the grid via the observer.
435     propagateTreeEntries(observer: Observer<HoldingsEntry>, node: HoldingsTreeNode) {
436         const entry = new HoldingsEntry();
437         entry.treeNode = node;
438         entry.index = this.gridIndex++;
439
440         switch (node.nodeType) {
441             case 'org':
442                 if (node.callNumCount === 0
443                     && !this.emptyLibsCheckbox.checked()) {
444                     return;
445                 }
446                 entry.locationLabel = node.target.shortname();
447                 entry.locationDepth = node.target.ou_type().depth();
448                 entry.copyCount = node.copyCount;
449                 entry.callNumCount = node.callNumCount;
450                 this.sortOrgNodeChildren(node);
451                 break;
452
453             case 'callNum':
454                 if (this.renderFromPrefs) {
455                     if (!this.callNumsCheckbox.checked()) {
456                         return;
457                     }
458                     if (node.copyCount === 0
459                         && !this.emptyCallNumsCheckbox.checked()) {
460                         return;
461                     }
462                 }
463                 entry.locationLabel = node.target._label;
464                 entry.locationDepth = node.parentNode.target.ou_type().depth() + 1;
465                 entry.callNumberLabel = entry.locationLabel;
466                 entry.callNum = node.target;
467                 entry.copyCount = node.copyCount;
468                 break;
469
470             case 'copy':
471                 entry.locationLabel = node.target.barcode();
472                 entry.locationDepth = node.parentNode.parentNode.target.ou_type().depth() + 2;
473                 entry.callNumberLabel = node.parentNode.target.label(); // TODO
474                 entry.callNum = node.parentNode.target;
475                 entry.copy = node.target;
476                 entry.circ = node.target._circ;
477                 break;
478         }
479
480         // Tell the grid about the node entry
481         observer.next(entry);
482
483         if (node.expanded) {
484             // Process the child nodes.
485             node.children.forEach(child =>
486                 this.propagateTreeEntries(observer, child));
487         }
488     }
489
490     // Turns the tree into a list of entries for grid display
491     flattenHoldingsTree(observer: Observer<HoldingsEntry>) {
492         this.gridIndex = 0;
493         this.setTreeCounts(this.holdingsTree.root);
494         this.propagateTreeEntries(observer, this.holdingsTree.root);
495         observer.complete();
496         this.renderFromPrefs = false;
497     }
498
499     // Grab call numbers, copies, and related data.
500     fetchHoldings(pager: Pager): Observable<any> {
501         if (!this.recordId) { return of([]); }
502
503         return new Observable<any>(observer => {
504
505             if (!this.refreshHoldings) {
506                 this.flattenHoldingsTree(observer);
507                 return;
508             }
509
510             this.itemCircsNeeded = [];
511
512             this.pcrud.search('acn',
513                 {   record: this.recordId,
514                     owning_lib: this.org.fullPath(this.contextOrg, true),
515                     deleted: 'f',
516                     label: {'!=' : '##URI##'}
517                 }, {
518                     flesh: 3,
519                     flesh_fields: {
520                         acp: ['status', 'location', 'circ_lib', 'parts', 'notes',
521                             'tags', 'age_protect', 'copy_alerts', 'latest_inventory'],
522                         acn: ['prefix', 'suffix', 'copies'],
523                         acli: ['inventory_workstation']
524                     }
525                 },
526                 {authoritative: true}
527             ).subscribe(
528                 callNum => this.appendCallNum(callNum),
529                 err => {},
530                 ()  => {
531                     this.refreshHoldings = false;
532                     this.fetchCircs().then(
533                         ok => this.flattenHoldingsTree(observer)
534                     );
535                 }
536             );
537         });
538     }
539
540     // Retrieve circulation objects for checked out items.
541     fetchCircs(): Promise<any> {
542         const copyIds = this.itemCircsNeeded.map(copy => copy.id());
543         if (copyIds.length === 0) { return Promise.resolve(); }
544
545         return this.pcrud.search('circ', {
546             target_copy: copyIds,
547             checkin_time: null
548         }).pipe(map(circ => {
549             const copy = this.itemCircsNeeded.filter(
550                 c => Number(c.id()) === Number(circ.target_copy()))[0];
551             copy._circ = circ;
552         })).toPromise();
553     }
554
555     // Compile prefix + label + suffix into field callNum._label;
556     setCallNumLabel(callNum: IdlObject) {
557         const pfx = callNum.prefix() ? callNum.prefix().label() : '';
558         const sfx = callNum.suffix() ? callNum.suffix().label() : '';
559         callNum._label = pfx ? pfx + ' ' : '';
560         callNum._label += callNum.label();
561         callNum._label += sfx ? ' ' + sfx : '';
562     }
563
564     // Create the tree node for the call number if it doesn't already exist.
565     // Do the same for its linked copies.
566     appendCallNum(callNum: IdlObject) {
567         let callNumNode = this.treeNodeCache.callNum[callNum.id()];
568         this.setCallNumLabel(callNum);
569
570         if (callNumNode) {
571             const pNode = this.treeNodeCache.org[callNum.owning_lib()];
572             if (callNumNode.parentNode.target.id() !== pNode.target.id()) {
573                 // Call number owning library changed.  Un-link it from the
574                 // previous org unit collection before adding to the new one.
575                 // XXX TODO: ^--
576                 callNumNode.parentNode = pNode;
577                 callNumNode.parentNode.children.push(callNumNode);
578             }
579         } else {
580             callNumNode = new HoldingsTreeNode();
581             callNumNode.nodeType = 'callNum';
582             callNumNode.parentNode = this.treeNodeCache.org[callNum.owning_lib()];
583             callNumNode.parentNode.children.push(callNumNode);
584             this.treeNodeCache.callNum[callNum.id()] = callNumNode;
585         }
586
587         callNumNode.target = callNum;
588
589         callNum.copies()
590             .filter((copy: IdlObject) => (copy.deleted() !== 't'))
591             .sort((a: IdlObject, b: IdlObject) => a.barcode() < b.barcode() ? -1 : 1)
592             .forEach((copy: IdlObject) => this.appendCopy(callNumNode, copy));
593     }
594
595     // Find or create a copy node.
596     appendCopy(callNumNode: HoldingsTreeNode, copy: IdlObject) {
597         let copyNode = this.treeNodeCache.copy[copy.id()];
598
599         if (copyNode) {
600             const oldParent = copyNode.parentNode;
601             if (oldParent.target.id() !== callNumNode.target.id()) {
602                 // TODO: copy changed owning call number.  Remove it from
603                 // the previous call number before adding to the new call number.
604                 copyNode.parentNode = callNumNode;
605                 callNumNode.children.push(copyNode);
606             }
607         } else {
608             // New node required
609             copyNode = new HoldingsTreeNode();
610             copyNode.nodeType = 'copy';
611             callNumNode.children.push(copyNode);
612             copyNode.parentNode = callNumNode;
613             this.treeNodeCache.copy[copy.id()] = copyNode;
614         }
615
616         copyNode.target = copy;
617         const stat = Number(copy.status().id());
618         copy._monograph_parts = '';
619         if (copy.parts().length > 0) {
620             copy._monograph_parts =
621                 copy.parts().map(p => p.label()).join(',');
622         }
623
624         if (stat === 1 /* checked out */ || stat === 16 /* long overdue */) {
625             // Avoid looking up circs on items that are not checked out.
626             this.itemCircsNeeded.push(copy);
627         }
628     }
629
630     // Which copies in the grid are selected.
631     selectedCopyIds(rows: HoldingsEntry[], skipStatus?: number): number[] {
632         return this.selectedCopies(rows, skipStatus).map(c => Number(c.id()));
633     }
634
635     selectedVolIds(rows: HoldingsEntry[]): number[] {
636         return rows
637             .filter(r => Boolean(r.callNum))
638             .map(r => Number(r.callNum.id()));
639     }
640
641     selectedCopies(rows: HoldingsEntry[], skipStatus?: number): IdlObject[] {
642         let copyRows = rows.filter(r => Boolean(r.copy)).map(r => r.copy);
643         if (skipStatus) {
644             copyRows = copyRows.filter(
645                 c => Number(c.status().id()) !== Number(skipStatus));
646         }
647         return copyRows;
648     }
649
650     selectedCallNumIds(rows: HoldingsEntry[]): number[] {
651         return this.selectedCallNums(rows).map(cn => cn.id());
652     }
653
654     selectedCallNums(rows: HoldingsEntry[]): IdlObject[] {
655         return rows
656             .filter(r => r.treeNode.nodeType === 'callNum')
657             .map(r => r.callNum);
658     }
659
660
661     async showMarkDamagedDialog(rows: HoldingsEntry[]) {
662         const copyIds = this.selectedCopyIds(rows, 14 /* ignore damaged */);
663
664         if (copyIds.length === 0) { return; }
665
666         let rowsModified = false;
667
668         const markNext = async(ids: number[]) => {
669             if (ids.length === 0) {
670                 return Promise.resolve();
671             }
672
673             this.markDamagedDialog.copyId = ids.pop();
674             return this.markDamagedDialog.open({size: 'lg'}).subscribe(
675                 ok => {
676                     if (ok) { rowsModified = true; }
677                     return markNext(ids);
678                 },
679                 dismiss => markNext(ids)
680             );
681         };
682
683         await markNext(copyIds);
684         if (rowsModified) {
685             this.refreshHoldings = true;
686             this.holdingsGrid.reload();
687         }
688     }
689
690     showMarkMissingDialog(rows: any[]) {
691         const copyIds = this.selectedCopyIds(rows, 4 /* ignore missing */);
692         if (copyIds.length > 0) {
693             this.markMissingDialog.copyIds = copyIds;
694             this.markMissingDialog.open({}).subscribe(
695                 rowsModified => {
696                     if (rowsModified) {
697                         this.refreshHoldings = true;
698                         this.holdingsGrid.reload();
699                     }
700                 },
701                 dismissed => {} // avoid console errors
702             );
703         }
704     }
705
706     // Mark record, library, and potentially the selected call number
707     // as the current transfer target.
708     markLibCnForTransfer(rows: HoldingsEntry[]) {
709         if (rows.length === 0) {
710             return;
711         }
712
713         // Action may only apply to a single org or call number row.
714         const node = rows[0].treeNode;
715         if (node.nodeType === 'copy') { return; }
716
717         let orgId: number;
718
719         if (node.nodeType === 'org') {
720             orgId = node.target.id();
721
722             // Clear call number target when performed on an org unit row
723             this.localStore.removeLocalItem('eg.cat.transfer_target_vol');
724
725         } else if (node.nodeType === 'callNum') {
726
727             // All call number nodes are children of org nodes.
728             orgId = node.parentNode.target.id();
729
730             // Add call number target when performed on a call number row.
731             this.localStore.setLocalItem(
732                 'eg.cat.transfer_target_vol', node.target.id());
733         }
734
735         // Track lib and record to support transfering items from
736         // a different bib record to this record at the selected
737         // owning lib.
738         this.localStore.setLocalItem('eg.cat.transfer_target_lib', orgId);
739         this.localStore.setLocalItem('eg.cat.transfer_target_record', this.recordId);
740     }
741
742     openAngJsWindow(path: string) {
743         const url = `/eg/staff/${path}`;
744         window.open(url, '_blank');
745     }
746
747     openItemHolds(rows: HoldingsEntry[]) {
748         if (rows.length > 0 && rows[0].copy) {
749             this.openAngJsWindow(`cat/item/${rows[0].copy.id()}/holds`);
750         }
751     }
752
753     openItemStatusList(rows: HoldingsEntry[]) {
754         const ids = this.selectedCopyIds(rows);
755         if (ids.length > 0) {
756             return this.openAngJsWindow(`cat/item/search/${ids.join(',')}`);
757         }
758     }
759
760     openItemStatus(rows: HoldingsEntry[]) {
761         if (rows.length > 0 && rows[0].copy) {
762            return this.openAngJsWindow(`cat/item/${rows[0].copy.id()}`);
763         }
764     }
765
766     openItemTriggeredEvents(rows: HoldingsEntry[]) {
767         if (rows.length > 0 && rows[0].copy) {
768            return this.openAngJsWindow(
769                `cat/item/${rows[0].copy.id()}/triggered_events`);
770         }
771     }
772
773     openItemPrintLabels(rows: HoldingsEntry[]) {
774         const ids = this.selectedCopyIds(rows);
775         if (ids.length === 0) { return; }
776
777         this.anonCache.setItem(null, 'print-labels-these-copies', {copies: ids})
778         .then(key => this.openAngJsWindow(`cat/printlabels/${key}`));
779     }
780
781     openHoldingEdit(rows: HoldingsEntry[], hideVols: boolean, hideCopies: boolean) {
782
783         // Avoid adding call number edit entries for call numbers
784         // that are already represented by selected items.
785
786         const copies = this.selectedCopies(rows);
787         const copyVols = copies.map(c => Number(c.call_number()));
788
789         const volIds = [];
790         this.selectedVolIds(rows).forEach(id => {
791             if (!copyVols.includes(id)) {
792                 volIds.push(id);
793             }
794         });
795
796         this.holdings.spawnAddHoldingsUi(
797             this.recordId,
798             volIds,
799             null,
800             copies.map(c => Number(c.id())),
801             hideCopies,
802             hideVols
803         );
804     }
805
806     openHoldingAdd(rows: HoldingsEntry[], addCallNums: boolean, addCopies: boolean) {
807
808         // The user may select a set of call numbers by selecting call
809         // number and/or item rows.  Owning libs for new call numbers may
810         // also come from org unit row selection.
811         const orgs = {};
812         const callNums = [];
813         rows.forEach(r => {
814             if (r.treeNode.nodeType === 'callNum') {
815                 callNums.push(r.callNum);
816
817             } else if (r.treeNode.nodeType === 'copy') {
818                 callNums.push(r.treeNode.parentNode.target);
819
820             } else if (r.treeNode.nodeType === 'org') {
821                 const org = r.treeNode.target;
822                 if (org.ou_type().can_have_vols() === 't') {
823                     orgs[org.id()] = true;
824                 }
825             }
826         });
827
828         if (addCopies && !addCallNums) {
829             // Adding copies to an existing set of call numbers.
830             if (callNums.length > 0) {
831                 const callNumIds = callNums.map(v => Number(v.id()));
832                 this.holdings.spawnAddHoldingsUi(this.recordId, callNumIds);
833             }
834
835         } else if (addCallNums) {
836             const entries = [];
837
838             // Use selected call numbers as basis for new call numbers.
839             callNums.forEach(v =>
840                 entries.push({label: v.label(), owner: v.owning_lib()}));
841
842             // Use selected org units as owning libs for new call numbers
843             Object.keys(orgs).forEach(id => entries.push({owner: id}));
844
845             if (entries.length === 0) {
846                 // Otherwise create new call numbers for "here"
847                 entries.push({owner: this.auth.user().ws_ou()});
848             }
849
850             this.holdings.spawnAddHoldingsUi(
851                 this.recordId, null, entries, null, !addCopies);
852         }
853     }
854
855     openItemNotes(rows: HoldingsEntry[], mode: string) {
856         const copyIds = this.selectedCopyIds(rows);
857         if (copyIds.length === 0) { return; }
858
859         this.copyAlertsDialog.copyIds = copyIds;
860         this.copyAlertsDialog.mode = mode;
861         this.copyAlertsDialog.open({size: 'lg'}).subscribe(
862             modified => {
863                 if (modified) {
864                     this.hardRefresh();
865                 }
866             }
867         );
868     }
869
870     openItemTags(rows: HoldingsEntry[]) {
871         const copyIds = this.selectedCopyIds(rows);
872         if (copyIds.length === 0) { return; }
873
874         this.copyTagsDialog.copyIds = copyIds;
875         this.copyTagsDialog.open({size: 'lg'}).subscribe(
876             modified => {
877                 if (modified) {
878                     this.hardRefresh();
879                 }
880             }
881         );
882     }
883
884     openReplaceBarcodeDialog(rows: HoldingsEntry[]) {
885         const ids = this.selectedCopyIds(rows);
886         if (ids.length === 0) { return; }
887         this.replaceBarcode.copyIds = ids;
888         this.replaceBarcode.open({}).subscribe(
889             modified => {
890                 if (modified) {
891                     this.hardRefresh();
892                 }
893             }
894         );
895     }
896
897     // mode 'callNums' -- only delete empty call numbers
898     // mode 'copies' -- only delete selected copies
899     // mode 'both' -- delete selected copies and selected call numbers, plus all
900     // copies linked to selected call numbers, regardless of whether they are selected.
901     deleteHoldings(rows: HoldingsEntry[], mode: 'callNums' | 'copies' | 'both') {
902         const callNumHash: any = {};
903
904         if (mode === 'callNums' || mode === 'both') {
905             // Collect the call numbers to be deleted.
906             rows.filter(r => r.treeNode.nodeType === 'callNum').forEach(r => {
907                 const callNum = this.idl.clone(r.callNum);
908                 if (mode === 'callNums') {
909                     if (callNum.copies().length > 0) {
910                         // cannot delete non-empty call number in this mode.
911                         return;
912                     }
913                 } else {
914                     callNum.copies().forEach(c => c.isdeleted(true));
915                 }
916                 callNum.isdeleted(true);
917                 callNumHash[callNum.id()] = callNum;
918             });
919         }
920
921         if (mode === 'copies' || mode === 'both') {
922             // Collect the copies to be deleted, including their call numbers
923             // since the API expects fleshed call number objects.
924             rows.filter(r => r.treeNode.nodeType === 'copy').forEach(r => {
925                 const callNum = r.treeNode.parentNode.target;
926                 if (!callNumHash[callNum.id()]) {
927                     callNumHash[callNum.id()] = this.idl.clone(callNum);
928                     callNumHash[callNum.id()].copies([]);
929                 }
930                 const copy = this.idl.clone(r.copy);
931                 copy.isdeleted(true);
932                 callNumHash[callNum.id()].copies().push(copy);
933             });
934         }
935
936         if (Object.keys(callNumHash).length === 0) {
937             // No data to process.
938             return;
939         }
940
941         // Note forceDeleteCopies should not be necessary here, since we
942         // manually marked all copies as deleted on deleted call numbers in
943         // "both" mode.
944         this.deleteHolding.forceDeleteCopies = mode === 'both';
945         this.deleteHolding.callNums = Object.values(callNumHash);
946         this.deleteHolding.open({size: 'sm'}).subscribe(
947             modified => {
948                 if (modified) {
949                     this.hardRefresh();
950                 }
951             }
952         );
953     }
954
955     requestItems(rows: HoldingsEntry[]) {
956         const copyIds = this.selectedCopyIds(rows);
957         if (copyIds.length === 0) { return; }
958         const params = {target: copyIds, holdFor: 'staff'};
959         this.router.navigate(['/staff/catalog/hold/C'], {queryParams: params});
960     }
961
962     openBucketDialog(rows: HoldingsEntry[]) {
963         const copyIds = this.selectedCopyIds(rows);
964         if (copyIds.length > 0) {
965             this.bucketDialog.bucketClass = 'copy';
966             this.bucketDialog.itemIds = copyIds;
967             this.bucketDialog.open({size: 'lg'});
968         }
969     }
970
971     openConjoinedDialog(rows: HoldingsEntry[]) {
972         const copyIds = this.selectedCopyIds(rows);
973         if (copyIds.length > 0) {
974             this.conjoinedDialog.copyIds = copyIds;
975             this.conjoinedDialog.open({size: 'sm'});
976         }
977     }
978
979     bookItems(rows: HoldingsEntry[]) {
980         const copyIds = this.selectedCopyIds(rows);
981         if (copyIds.length > 0) {
982             this.router.navigate(
983                 ['staff', 'booking', 'create_reservation', 'for_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
984             );
985         }
986     }
987
988     makeBookable(rows: HoldingsEntry[]) {
989         const copyIds = this.selectedCopyIds(rows);
990         if (copyIds.length > 0) {
991             this.makeBookableDialog.copyIds = copyIds;
992             this.makeBookableDialog.open({});
993         }
994     }
995
996     manageReservations(rows: HoldingsEntry[]) {
997         const copyIds = this.selectedCopyIds(rows);
998         if (copyIds.length > 0) {
999             this.router.navigate(
1000                 ['staff', 'booking', 'manage_reservations', 'by_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
1001             );
1002         }
1003     }
1004
1005     transferSelectedItems(rows: HoldingsEntry[]) {
1006         if (rows.length === 0) { return; }
1007
1008         const cnId =
1009             this.localStore.getLocalItem('eg.cat.transfer_target_vol');
1010
1011         const orgId =
1012             this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1013
1014         const recId =
1015             this.localStore.getLocalItem('eg.cat.transfer_target_record');
1016
1017         let promise;
1018
1019         if (cnId) { // Direct call number transfer
1020
1021             const itemIds = this.selectedCopyIds(rows);
1022             promise = this.transferItems.transferItems(itemIds, cnId);
1023
1024         } else if (orgId && recId) { // "Auto" transfer
1025
1026             // Clone the items to be modified to avoid any unexpected
1027             // modifications and fesh the call numbers.
1028             const items = this.idl.clone(this.selectedCopies(rows));
1029             items.forEach(i => i.call_number(
1030                 this.treeNodeCache.callNum[i.call_number()].target));
1031
1032             console.log(items);
1033             promise = this.transferItems.autoTransferItems(items, recId, orgId);
1034
1035         } else {
1036             promise = this.transferAlert.open().toPromise();
1037         }
1038
1039         promise.then(success => success ?  this.hardRefresh() : null);
1040     }
1041
1042     transferSelectedHoldings(rows: HoldingsEntry[]) {
1043         const callNums = this.selectedCallNums(rows);
1044         if (callNums.length === 0) { return; }
1045
1046         const orgId =
1047             this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1048
1049         let recId =
1050             this.localStore.getLocalItem('eg.cat.transfer_target_record');
1051
1052         if (orgId) {
1053             // When transferring holdings (call numbers) between org units,
1054             // limit transfers to within the current record.
1055             recId = this.recordId;
1056
1057         } else if (!recId) {
1058             // No destinations applied.
1059             return this.transferAlert.open();
1060         }
1061
1062         this.transferHoldings.targetRecId = recId;
1063         this.transferHoldings.targetOrgId = orgId;
1064         this.transferHoldings.callNums = callNums;
1065
1066         this.transferHoldings.transferHoldings()
1067         .then(success => success ?  this.hardRefresh() : null);
1068     }
1069 }
1070