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';
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';
52 parentNode: HoldingsTreeNode;
62 root: HoldingsTreeNode;
64 this.root = new HoldingsTreeNode();
68 export class HoldingsEntry {
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;
80 treeNode: HoldingsTreeNode;
84 selector: 'eg-holdings-maintenance',
85 templateUrl: 'holdings.component.html',
86 styleUrls: ['holdings.component.css'],
87 encapsulation: ViewEncapsulation.None
89 export class HoldingsMaintenanceComponent implements OnInit {
92 gridDataSource: GridDataSource;
93 gridTemplateContext: any;
94 @ViewChild('holdingsGrid', { static: true }) holdingsGrid: GridComponent;
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;
130 holdingsTree: HoldingsTree;
132 // nodeType => id => tree node cache
133 treeNodeCache: {[nodeType: string]: {[id: number]: HoldingsTreeNode}};
135 // When true and a grid reload is called, the holdings data will be
136 // re-fetched from the server.
137 refreshHoldings: boolean;
139 // Used as a row identifier in th grid, since we're mixing object types.
142 // List of copies whose due date we need to retrieve.
143 itemCircsNeeded: IdlObject[];
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;
150 rowClassCallback: (row: any) => string;
151 cellTextGenerator: GridCellTextGenerator;
153 private _recId: number;
154 @Input() set recordId(id: number) {
156 // Only force new data collection when recordId()
157 // is invoked after ngInit() has already run.
162 get recordId(): number {
166 contextOrg: IdlObject;
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;
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
186 // Set some sane defaults before settings are loaded.
187 this.gridDataSource = new GridDataSource();
188 this.refreshHoldings = true;
189 this.renderFromPrefs = true;
191 // TODO: need a separate setting for this?
192 this.contextOrg = this.staffCat.searchContext.searchOrg;
194 this.rowClassCallback = (row: any): string => {
197 return 'holdings-copy-row';
199 return 'holdings-callNum-row';
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();
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) : ''
216 this.gridTemplateContext = {
217 toggleExpandRow: (row: HoldingsEntry) => {
218 row.treeNode.expanded = !row.treeNode.expanded;
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);
227 traverse(row.treeNode);
230 this.holdingsGrid.reload();
233 copyIsHoldable: (copy: IdlObject): boolean => {
234 return copy.holdable() === 't'
235 && copy.location().holdable() === 't'
236 && copy.status().holdable() === 't';
242 this.initDone = true;
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();
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'
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; }
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']);
268 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
269 if (!this.contextOrgLoaded) { return empty(); }
270 return this.fetchHoldings(pager);
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;
282 this.renderFromPrefs = true;
283 this.refreshHoldings = true;
284 this.initHoldingsTree();
285 this.holdingsGrid.reload();
288 toggleShowCopies(value: boolean) {
289 this.store.setItem('cat.holdings_show_copies', value);
291 // Showing copies implies showing call numbers
292 this.callNumsCheckbox.checked(true);
294 this.renderFromPrefs = true;
295 this.holdingsGrid.reload();
298 toggleShowCallNums(value: boolean) {
299 this.store.setItem('cat.holdings_show_vols', value);
301 // Hiding call numbers implies hiding empty call numbers and copies.
302 this.copiesCheckbox.checked(false);
303 this.emptyCallNumsCheckbox.checked(false);
305 this.renderFromPrefs = true;
306 this.holdingsGrid.reload();
309 toggleShowEmptyCallNums(value: boolean) {
310 this.store.setItem('cat.holdings_show_empty', value);
312 this.callNumsCheckbox.checked(true);
314 this.renderFromPrefs = true;
315 this.holdingsGrid.reload();
318 toggleShowEmptyLibs(value: boolean) {
319 this.store.setItem('cat.holdings_show_empty_org', value);
320 this.renderFromPrefs = true;
321 this.holdingsGrid.reload();
324 onRowActivate(row: any) {
326 // Launch copy editor?
328 this.gridTemplateContext.toggleExpandRow(row);
334 const visibleOrgs = this.org.fullPath(this.contextOrg, true);
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
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);
352 this.treeNodeCache = {
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;
363 traverseOrg(this.holdingsTree.root);
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;
376 } else if (b.nodeType === 'org') {
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;
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) {
390 if (node.nodeType === 'org') {
392 node.callNumCount = 0;
393 } else if (node.nodeType === 'callNum') {
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') {
406 hasChildOrgWithData = child.callNumCount > 0;
407 hasChildOrgSansData = child.callNumCount === 0;
408 node.callNumCount += child.callNumCount;
410 } else if (node.nodeType === 'callNum') {
411 node.copyCount = node.children.length;
412 if (this.renderFromPrefs) {
413 node.expanded = this.copiesCheckbox.checked();
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;
428 node.expanded = false;
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++;
440 switch (node.nodeType) {
442 if (node.callNumCount === 0
443 && !this.emptyLibsCheckbox.checked()) {
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);
454 if (this.renderFromPrefs) {
455 if (!this.callNumsCheckbox.checked()) {
458 if (node.copyCount === 0
459 && !this.emptyCallNumsCheckbox.checked()) {
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;
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;
480 // Tell the grid about the node entry
481 observer.next(entry);
484 // Process the child nodes.
485 node.children.forEach(child =>
486 this.propagateTreeEntries(observer, child));
490 // Turns the tree into a list of entries for grid display
491 flattenHoldingsTree(observer: Observer<HoldingsEntry>) {
493 this.setTreeCounts(this.holdingsTree.root);
494 this.propagateTreeEntries(observer, this.holdingsTree.root);
496 this.renderFromPrefs = false;
499 // Grab call numbers, copies, and related data.
500 fetchHoldings(pager: Pager): Observable<any> {
501 if (!this.recordId) { return of([]); }
503 return new Observable<any>(observer => {
505 if (!this.refreshHoldings) {
506 this.flattenHoldingsTree(observer);
510 this.itemCircsNeeded = [];
511 // Track vol IDs for the current fetch so we can prune
512 // any that were deleted in an out-of-band update.
513 const volsFetched: number[] = [];
515 this.pcrud.search('acn',
516 { record: this.recordId,
517 owning_lib: this.org.fullPath(this.contextOrg, true),
519 label: {'!=' : '##URI##'}
523 acp: ['status', 'location', 'circ_lib', 'parts', 'notes',
524 'tags', 'age_protect', 'copy_alerts', 'latest_inventory'],
525 acn: ['prefix', 'suffix', 'copies'],
526 acli: ['inventory_workstation']
529 {authoritative: true}
532 this.appendCallNum(callNum);
533 volsFetched.push(callNum.id());
537 this.refreshHoldings = false;
538 this.pruneVols(volsFetched);
539 this.fetchCircs().then(
540 ok => this.flattenHoldingsTree(observer)
547 // Remove vols that were deleted out-of-band, via edit, merge, etc.
548 pruneVols(volsFetched: number[]) {
550 const toRemove: number[] = []; // avoid modifying mid-loop
551 Object.keys(this.treeNodeCache.callNum).forEach(volId => {
552 const id = Number(volId);
553 if (!volsFetched.includes(id)) {
558 if (toRemove.length === 0) { return; }
560 const pruneNodes = (node: HoldingsTreeNode) => {
561 if (node.nodeType === 'callNum' &&
562 toRemove.includes(node.target.id())) {
564 console.debug('pruning deleted vol:', node.target.id());
566 // Remove this node from the parents list of children
567 node.parentNode.children =
568 node.parentNode.children.filter(
569 c => c.target.id() !== node.target.id());
572 node.children.forEach(c => pruneNodes(c));
577 toRemove.forEach(volId => delete this.treeNodeCache.callNum[volId]);
580 pruneNodes(this.holdingsTree.root);
582 // refresh tree / grid
583 this.holdingsGrid.reload();
586 // Retrieve circulation objects for checked out items.
587 fetchCircs(): Promise<any> {
588 const copyIds = this.itemCircsNeeded.map(copy => copy.id());
589 if (copyIds.length === 0) { return Promise.resolve(); }
591 return this.pcrud.search('circ', {
592 target_copy: copyIds,
594 }).pipe(map(circ => {
595 const copy = this.itemCircsNeeded.filter(
596 c => Number(c.id()) === Number(circ.target_copy()))[0];
601 // Compile prefix + label + suffix into field callNum._label;
602 setCallNumLabel(callNum: IdlObject) {
603 const pfx = callNum.prefix() ? callNum.prefix().label() : '';
604 const sfx = callNum.suffix() ? callNum.suffix().label() : '';
605 callNum._label = pfx ? pfx + ' ' : '';
606 callNum._label += callNum.label();
607 callNum._label += sfx ? ' ' + sfx : '';
610 // Create the tree node for the call number if it doesn't already exist.
611 // Do the same for its linked copies.
612 appendCallNum(callNum: IdlObject) {
613 let callNumNode = this.treeNodeCache.callNum[callNum.id()];
614 this.setCallNumLabel(callNum);
617 const pNode = this.treeNodeCache.org[callNum.owning_lib()];
618 if (callNumNode.parentNode.target.id() !== pNode.target.id()) {
619 callNumNode.parentNode = pNode;
620 callNumNode.parentNode.children.push(callNumNode);
623 callNumNode = new HoldingsTreeNode();
624 callNumNode.nodeType = 'callNum';
625 callNumNode.parentNode = this.treeNodeCache.org[callNum.owning_lib()];
626 callNumNode.parentNode.children.push(callNumNode);
627 this.treeNodeCache.callNum[callNum.id()] = callNumNode;
630 callNumNode.target = callNum;
633 .filter((copy: IdlObject) => (copy.deleted() !== 't'))
634 .sort((a: IdlObject, b: IdlObject) => a.barcode() < b.barcode() ? -1 : 1)
635 .forEach((copy: IdlObject) => this.appendCopy(callNumNode, copy));
638 // Find or create a copy node.
639 appendCopy(callNumNode: HoldingsTreeNode, copy: IdlObject) {
640 let copyNode = this.treeNodeCache.copy[copy.id()];
643 const oldParent = copyNode.parentNode;
644 if (oldParent.target.id() !== callNumNode.target.id()) {
645 // TODO: copy changed owning call number. Remove it from
646 // the previous call number before adding to the new call number.
647 copyNode.parentNode = callNumNode;
648 callNumNode.children.push(copyNode);
652 copyNode = new HoldingsTreeNode();
653 copyNode.nodeType = 'copy';
654 callNumNode.children.push(copyNode);
655 copyNode.parentNode = callNumNode;
656 this.treeNodeCache.copy[copy.id()] = copyNode;
659 copyNode.target = copy;
660 const stat = Number(copy.status().id());
661 copy._monograph_parts = '';
662 if (copy.parts().length > 0) {
663 copy._monograph_parts =
664 copy.parts().map(p => p.label()).join(',');
667 if (stat === 1 /* checked out */ || stat === 16 /* long overdue */) {
668 // Avoid looking up circs on items that are not checked out.
669 this.itemCircsNeeded.push(copy);
673 // Which copies in the grid are selected.
674 selectedCopyIds(rows: HoldingsEntry[], skipStatus?: number): number[] {
675 return this.selectedCopies(rows, skipStatus).map(c => Number(c.id()));
678 selectedVolIds(rows: HoldingsEntry[]): number[] {
680 .filter(r => Boolean(r.callNum))
681 .map(r => Number(r.callNum.id()));
684 selectedCopies(rows: HoldingsEntry[], skipStatus?: number): IdlObject[] {
685 let copyRows = rows.filter(r => Boolean(r.copy)).map(r => r.copy);
687 copyRows = copyRows.filter(
688 c => Number(c.status().id()) !== Number(skipStatus));
693 selectedCallNumIds(rows: HoldingsEntry[]): number[] {
694 return this.selectedCallNums(rows).map(cn => cn.id());
697 selectedCallNums(rows: HoldingsEntry[]): IdlObject[] {
699 .filter(r => r.treeNode.nodeType === 'callNum')
700 .map(r => r.callNum);
704 async showMarkDamagedDialog(rows: HoldingsEntry[]) {
705 const copyIds = this.selectedCopyIds(rows, 14 /* ignore damaged */);
707 if (copyIds.length === 0) { return; }
709 let rowsModified = false;
711 const markNext = async(ids: number[]) => {
712 if (ids.length === 0) {
713 return Promise.resolve();
716 this.markDamagedDialog.copyId = ids.pop();
717 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
719 if (ok) { rowsModified = true; }
720 return markNext(ids);
722 dismiss => markNext(ids)
726 await markNext(copyIds);
728 this.refreshHoldings = true;
729 this.holdingsGrid.reload();
733 showMarkMissingDialog(rows: any[]) {
734 const copyIds = this.selectedCopyIds(rows, 4 /* ignore missing */);
735 if (copyIds.length > 0) {
736 this.markMissingDialog.copyIds = copyIds;
737 this.markMissingDialog.open({}).subscribe(
740 this.refreshHoldings = true;
741 this.holdingsGrid.reload();
744 dismissed => {} // avoid console errors
749 // Mark record, library, and potentially the selected call number
750 // as the current transfer target.
751 markLibCnForTransfer(rows: HoldingsEntry[]) {
752 if (rows.length === 0) {
756 // Action may only apply to a single org or call number row.
757 const node = rows[0].treeNode;
758 if (node.nodeType === 'copy') { return; }
762 if (node.nodeType === 'org') {
763 orgId = node.target.id();
765 // Clear call number target when performed on an org unit row
766 this.localStore.removeLocalItem('eg.cat.transfer_target_vol');
768 } else if (node.nodeType === 'callNum') {
770 // All call number nodes are children of org nodes.
771 orgId = node.parentNode.target.id();
773 // Add call number target when performed on a call number row.
774 this.localStore.setLocalItem(
775 'eg.cat.transfer_target_vol', node.target.id());
778 // Track lib and record to support transfering items from
779 // a different bib record to this record at the selected
781 this.localStore.setLocalItem('eg.cat.transfer_target_lib', orgId);
782 this.localStore.setLocalItem('eg.cat.transfer_target_record', this.recordId);
785 openAngJsWindow(path: string) {
786 const url = `/eg/staff/${path}`;
787 window.open(url, '_blank');
790 openItemHolds(rows: HoldingsEntry[]) {
791 if (rows.length > 0 && rows[0].copy) {
792 this.openAngJsWindow(`cat/item/${rows[0].copy.id()}/holds`);
796 openItemStatusList(rows: HoldingsEntry[]) {
797 const ids = this.selectedCopyIds(rows);
798 if (ids.length > 0) {
799 return this.openAngJsWindow(`cat/item/search/${ids.join(',')}`);
803 openItemStatus(rows: HoldingsEntry[]) {
804 if (rows.length > 0 && rows[0].copy) {
805 return this.openAngJsWindow(`cat/item/${rows[0].copy.id()}`);
809 openItemTriggeredEvents(rows: HoldingsEntry[]) {
810 if (rows.length > 0 && rows[0].copy) {
811 return this.openAngJsWindow(
812 `cat/item/${rows[0].copy.id()}/triggered_events`);
816 openItemPrintLabels(rows: HoldingsEntry[]) {
817 const ids = this.selectedCopyIds(rows);
818 if (ids.length === 0) { return; }
820 this.anonCache.setItem(null, 'print-labels-these-copies', {copies: ids})
821 .then(key => this.openAngJsWindow(`cat/printlabels/${key}`));
824 openHoldingEdit(rows: HoldingsEntry[], hideVols: boolean, hideCopies: boolean) {
826 // Avoid adding call number edit entries for call numbers
827 // that are already represented by selected items.
829 const copies = this.selectedCopies(rows);
830 const copyVols = copies.map(c => Number(c.call_number()));
833 this.selectedVolIds(rows).forEach(id => {
834 if (!copyVols.includes(id)) {
839 this.holdings.spawnAddHoldingsUi(
843 copies.map(c => Number(c.id())),
849 openHoldingAdd(rows: HoldingsEntry[], addCallNums: boolean, addCopies: boolean) {
851 // The user may select a set of call numbers by selecting call
852 // number and/or item rows. Owning libs for new call numbers may
853 // also come from org unit row selection.
857 if (r.treeNode.nodeType === 'callNum') {
858 callNums.push(r.callNum);
860 } else if (r.treeNode.nodeType === 'copy') {
861 callNums.push(r.treeNode.parentNode.target);
863 } else if (r.treeNode.nodeType === 'org') {
864 const org = r.treeNode.target;
865 if (org.ou_type().can_have_vols() === 't') {
866 orgs[org.id()] = true;
871 if (addCopies && !addCallNums) {
872 // Adding copies to an existing set of call numbers.
873 if (callNums.length > 0) {
874 const callNumIds = callNums.map(v => Number(v.id()));
875 this.holdings.spawnAddHoldingsUi(this.recordId, callNumIds);
878 } else if (addCallNums) {
881 // Use selected call numbers as basis for new call numbers.
882 callNums.forEach(v =>
883 entries.push({label: v.label(), owner: v.owning_lib()}));
885 // Use selected org units as owning libs for new call numbers
886 Object.keys(orgs).forEach(id => entries.push({owner: id}));
888 if (entries.length === 0) {
889 // Otherwise create new call numbers for "here"
890 entries.push({owner: this.auth.user().ws_ou()});
893 this.holdings.spawnAddHoldingsUi(
894 this.recordId, null, entries, null, !addCopies);
898 openItemNotes(rows: HoldingsEntry[], mode: string) {
899 const copyIds = this.selectedCopyIds(rows);
900 if (copyIds.length === 0) { return; }
902 this.copyAlertsDialog.copyIds = copyIds;
903 this.copyAlertsDialog.mode = mode;
904 this.copyAlertsDialog.open({size: 'lg'}).subscribe(
913 openItemTags(rows: HoldingsEntry[]) {
914 const copyIds = this.selectedCopyIds(rows);
915 if (copyIds.length === 0) { return; }
917 this.copyTagsDialog.copyIds = copyIds;
918 this.copyTagsDialog.open({size: 'lg'}).subscribe(
927 openReplaceBarcodeDialog(rows: HoldingsEntry[]) {
928 const ids = this.selectedCopyIds(rows);
929 if (ids.length === 0) { return; }
930 this.replaceBarcode.copyIds = ids;
931 this.replaceBarcode.open({}).subscribe(
940 // mode 'callNums' -- only delete empty call numbers
941 // mode 'copies' -- only delete selected copies
942 // mode 'both' -- delete selected copies and selected call numbers, plus all
943 // copies linked to selected call numbers, regardless of whether they are selected.
944 deleteHoldings(rows: HoldingsEntry[], mode: 'callNums' | 'copies' | 'both') {
945 const callNumHash: any = {};
947 if (mode === 'callNums' || mode === 'both') {
948 // Collect the call numbers to be deleted.
949 rows.filter(r => r.treeNode.nodeType === 'callNum').forEach(r => {
950 const callNum = this.idl.clone(r.callNum);
951 if (mode === 'callNums') {
952 if (callNum.copies().length > 0) {
953 // cannot delete non-empty call number in this mode.
957 callNum.copies().forEach(c => c.isdeleted(true));
959 callNum.isdeleted(true);
960 callNumHash[callNum.id()] = callNum;
964 if (mode === 'copies' || mode === 'both') {
965 // Collect the copies to be deleted, including their call numbers
966 // since the API expects fleshed call number objects.
967 rows.filter(r => r.treeNode.nodeType === 'copy').forEach(r => {
968 const callNum = r.treeNode.parentNode.target;
969 if (!callNumHash[callNum.id()]) {
970 callNumHash[callNum.id()] = this.idl.clone(callNum);
971 callNumHash[callNum.id()].copies([]);
973 const copy = this.idl.clone(r.copy);
974 copy.isdeleted(true);
975 callNumHash[callNum.id()].copies().push(copy);
979 if (Object.keys(callNumHash).length === 0) {
980 // No data to process.
984 // Note forceDeleteCopies should not be necessary here, since we
985 // manually marked all copies as deleted on deleted call numbers in
987 this.deleteHolding.forceDeleteCopies = mode === 'both';
988 this.deleteHolding.callNums = Object.values(callNumHash);
989 this.deleteHolding.open({size: 'sm'}).subscribe(
998 requestItems(rows: HoldingsEntry[]) {
999 const copyIds = this.selectedCopyIds(rows);
1000 if (copyIds.length === 0) { return; }
1001 const params = {target: copyIds, holdFor: 'staff'};
1002 this.router.navigate(['/staff/catalog/hold/C'], {queryParams: params});
1005 openBucketDialog(rows: HoldingsEntry[]) {
1006 const copyIds = this.selectedCopyIds(rows);
1007 if (copyIds.length > 0) {
1008 this.bucketDialog.bucketClass = 'copy';
1009 this.bucketDialog.itemIds = copyIds;
1010 this.bucketDialog.open({size: 'lg'});
1014 openConjoinedDialog(rows: HoldingsEntry[]) {
1015 const copyIds = this.selectedCopyIds(rows);
1016 if (copyIds.length > 0) {
1017 this.conjoinedDialog.copyIds = copyIds;
1018 this.conjoinedDialog.open({size: 'sm'});
1022 bookItems(rows: HoldingsEntry[]) {
1023 const copyIds = this.selectedCopyIds(rows);
1024 if (copyIds.length > 0) {
1025 this.router.navigate(
1026 ['staff', 'booking', 'create_reservation', 'for_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
1031 makeBookable(rows: HoldingsEntry[]) {
1032 const copyIds = this.selectedCopyIds(rows);
1033 if (copyIds.length > 0) {
1034 this.makeBookableDialog.copyIds = copyIds;
1035 this.makeBookableDialog.open({});
1039 manageReservations(rows: HoldingsEntry[]) {
1040 const copyIds = this.selectedCopyIds(rows);
1041 if (copyIds.length > 0) {
1042 this.router.navigate(
1043 ['staff', 'booking', 'manage_reservations', 'by_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
1048 transferSelectedItems(rows: HoldingsEntry[]) {
1049 if (rows.length === 0) { return; }
1052 this.localStore.getLocalItem('eg.cat.transfer_target_vol');
1055 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1058 this.localStore.getLocalItem('eg.cat.transfer_target_record');
1062 if (cnId) { // Direct call number transfer
1064 const itemIds = this.selectedCopyIds(rows);
1065 promise = this.transferItems.transferItems(itemIds, cnId);
1067 } else if (orgId && recId) { // "Auto" transfer
1069 // Clone the items to be modified to avoid any unexpected
1070 // modifications and fesh the call numbers.
1071 const items = this.idl.clone(this.selectedCopies(rows));
1072 items.forEach(i => i.call_number(
1073 this.treeNodeCache.callNum[i.call_number()].target));
1076 promise = this.transferItems.autoTransferItems(items, recId, orgId);
1079 promise = this.transferAlert.open().toPromise();
1082 promise.then(success => success ? this.hardRefresh() : null);
1085 transferSelectedHoldings(rows: HoldingsEntry[]) {
1086 const callNums = this.selectedCallNums(rows);
1087 if (callNums.length === 0) { return; }
1090 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1093 this.localStore.getLocalItem('eg.cat.transfer_target_record');
1096 // When transferring holdings (call numbers) between org units,
1097 // limit transfers to within the current record.
1098 recId = this.recordId;
1100 } else if (!recId) {
1101 // No destinations applied.
1102 return this.transferAlert.open();
1105 this.transferHoldings.targetRecId = recId;
1106 this.transferHoldings.targetOrgId = orgId;
1107 this.transferHoldings.callNums = callNums;
1109 this.transferHoldings.transferHoldings()
1110 .then(success => success ? this.hardRefresh() : null);