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 = [];
512 this.pcrud.search('acn',
513 { record: this.recordId,
514 owning_lib: this.org.fullPath(this.contextOrg, true),
516 label: {'!=' : '##URI##'}
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']
526 {authoritative: true}
528 callNum => this.appendCallNum(callNum),
531 this.refreshHoldings = false;
532 this.fetchCircs().then(
533 ok => this.flattenHoldingsTree(observer)
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(); }
545 return this.pcrud.search('circ', {
546 target_copy: copyIds,
548 }).pipe(map(circ => {
549 const copy = this.itemCircsNeeded.filter(
550 c => Number(c.id()) === Number(circ.target_copy()))[0];
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 : '';
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);
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.
576 callNumNode.parentNode = pNode;
577 callNumNode.parentNode.children.push(callNumNode);
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;
587 callNumNode.target = callNum;
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));
595 // Find or create a copy node.
596 appendCopy(callNumNode: HoldingsTreeNode, copy: IdlObject) {
597 let copyNode = this.treeNodeCache.copy[copy.id()];
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);
609 copyNode = new HoldingsTreeNode();
610 copyNode.nodeType = 'copy';
611 callNumNode.children.push(copyNode);
612 copyNode.parentNode = callNumNode;
613 this.treeNodeCache.copy[copy.id()] = copyNode;
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(',');
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);
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()));
635 selectedVolIds(rows: HoldingsEntry[]): number[] {
637 .filter(r => Boolean(r.callNum))
638 .map(r => Number(r.callNum.id()));
641 selectedCopies(rows: HoldingsEntry[], skipStatus?: number): IdlObject[] {
642 let copyRows = rows.filter(r => Boolean(r.copy)).map(r => r.copy);
644 copyRows = copyRows.filter(
645 c => Number(c.status().id()) !== Number(skipStatus));
650 selectedCallNumIds(rows: HoldingsEntry[]): number[] {
651 return this.selectedCallNums(rows).map(cn => cn.id());
654 selectedCallNums(rows: HoldingsEntry[]): IdlObject[] {
656 .filter(r => r.treeNode.nodeType === 'callNum')
657 .map(r => r.callNum);
661 async showMarkDamagedDialog(rows: HoldingsEntry[]) {
662 const copyIds = this.selectedCopyIds(rows, 14 /* ignore damaged */);
664 if (copyIds.length === 0) { return; }
666 let rowsModified = false;
668 const markNext = async(ids: number[]) => {
669 if (ids.length === 0) {
670 return Promise.resolve();
673 this.markDamagedDialog.copyId = ids.pop();
674 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
676 if (ok) { rowsModified = true; }
677 return markNext(ids);
679 dismiss => markNext(ids)
683 await markNext(copyIds);
685 this.refreshHoldings = true;
686 this.holdingsGrid.reload();
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(
697 this.refreshHoldings = true;
698 this.holdingsGrid.reload();
701 dismissed => {} // avoid console errors
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) {
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; }
719 if (node.nodeType === 'org') {
720 orgId = node.target.id();
722 // Clear call number target when performed on an org unit row
723 this.localStore.removeLocalItem('eg.cat.transfer_target_vol');
725 } else if (node.nodeType === 'callNum') {
727 // All call number nodes are children of org nodes.
728 orgId = node.parentNode.target.id();
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());
735 // Track lib and record to support transfering items from
736 // a different bib record to this record at the selected
738 this.localStore.setLocalItem('eg.cat.transfer_target_lib', orgId);
739 this.localStore.setLocalItem('eg.cat.transfer_target_record', this.recordId);
742 openAngJsWindow(path: string) {
743 const url = `/eg/staff/${path}`;
744 window.open(url, '_blank');
747 openItemHolds(rows: HoldingsEntry[]) {
748 if (rows.length > 0 && rows[0].copy) {
749 this.openAngJsWindow(`cat/item/${rows[0].copy.id()}/holds`);
753 openItemStatusList(rows: HoldingsEntry[]) {
754 const ids = this.selectedCopyIds(rows);
755 if (ids.length > 0) {
756 return this.openAngJsWindow(`cat/item/search/${ids.join(',')}`);
760 openItemStatus(rows: HoldingsEntry[]) {
761 if (rows.length > 0 && rows[0].copy) {
762 return this.openAngJsWindow(`cat/item/${rows[0].copy.id()}`);
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`);
773 openItemPrintLabels(rows: HoldingsEntry[]) {
774 const ids = this.selectedCopyIds(rows);
775 if (ids.length === 0) { return; }
777 this.anonCache.setItem(null, 'print-labels-these-copies', {copies: ids})
778 .then(key => this.openAngJsWindow(`cat/printlabels/${key}`));
781 openHoldingEdit(rows: HoldingsEntry[], hideVols: boolean, hideCopies: boolean) {
783 // Avoid adding call number edit entries for call numbers
784 // that are already represented by selected items.
786 const copies = this.selectedCopies(rows);
787 const copyVols = copies.map(c => Number(c.call_number()));
790 this.selectedVolIds(rows).forEach(id => {
791 if (!copyVols.includes(id)) {
796 this.holdings.spawnAddHoldingsUi(
800 copies.map(c => Number(c.id())),
806 openHoldingAdd(rows: HoldingsEntry[], addCallNums: boolean, addCopies: boolean) {
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.
814 if (r.treeNode.nodeType === 'callNum') {
815 callNums.push(r.callNum);
817 } else if (r.treeNode.nodeType === 'copy') {
818 callNums.push(r.treeNode.parentNode.target);
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;
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);
835 } else if (addCallNums) {
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()}));
842 // Use selected org units as owning libs for new call numbers
843 Object.keys(orgs).forEach(id => entries.push({owner: id}));
845 if (entries.length === 0) {
846 // Otherwise create new call numbers for "here"
847 entries.push({owner: this.auth.user().ws_ou()});
850 this.holdings.spawnAddHoldingsUi(
851 this.recordId, null, entries, null, !addCopies);
855 openItemNotes(rows: HoldingsEntry[], mode: string) {
856 const copyIds = this.selectedCopyIds(rows);
857 if (copyIds.length === 0) { return; }
859 this.copyAlertsDialog.copyIds = copyIds;
860 this.copyAlertsDialog.mode = mode;
861 this.copyAlertsDialog.open({size: 'lg'}).subscribe(
870 openItemTags(rows: HoldingsEntry[]) {
871 const copyIds = this.selectedCopyIds(rows);
872 if (copyIds.length === 0) { return; }
874 this.copyTagsDialog.copyIds = copyIds;
875 this.copyTagsDialog.open({size: 'lg'}).subscribe(
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(
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 = {};
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.
914 callNum.copies().forEach(c => c.isdeleted(true));
916 callNum.isdeleted(true);
917 callNumHash[callNum.id()] = callNum;
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([]);
930 const copy = this.idl.clone(r.copy);
931 copy.isdeleted(true);
932 callNumHash[callNum.id()].copies().push(copy);
936 if (Object.keys(callNumHash).length === 0) {
937 // No data to process.
941 // Note forceDeleteCopies should not be necessary here, since we
942 // manually marked all copies as deleted on deleted call numbers in
944 this.deleteHolding.forceDeleteCopies = mode === 'both';
945 this.deleteHolding.callNums = Object.values(callNumHash);
946 this.deleteHolding.open({size: 'sm'}).subscribe(
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});
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'});
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'});
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()]
988 makeBookable(rows: HoldingsEntry[]) {
989 const copyIds = this.selectedCopyIds(rows);
990 if (copyIds.length > 0) {
991 this.makeBookableDialog.copyIds = copyIds;
992 this.makeBookableDialog.open({});
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()]
1005 transferSelectedItems(rows: HoldingsEntry[]) {
1006 if (rows.length === 0) { return; }
1009 this.localStore.getLocalItem('eg.cat.transfer_target_vol');
1012 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1015 this.localStore.getLocalItem('eg.cat.transfer_target_record');
1019 if (cnId) { // Direct call number transfer
1021 const itemIds = this.selectedCopyIds(rows);
1022 promise = this.transferItems.transferItems(itemIds, cnId);
1024 } else if (orgId && recId) { // "Auto" transfer
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));
1033 promise = this.transferItems.autoTransferItems(items, recId, orgId);
1036 promise = this.transferAlert.open().toPromise();
1039 promise.then(success => success ? this.hardRefresh() : null);
1042 transferSelectedHoldings(rows: HoldingsEntry[]) {
1043 const callNums = this.selectedCallNums(rows);
1044 if (callNums.length === 0) { return; }
1047 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1050 this.localStore.getLocalItem('eg.cat.transfer_target_record');
1053 // When transferring holdings (call numbers) between org units,
1054 // limit transfers to within the current record.
1055 recId = this.recordId;
1057 } else if (!recId) {
1058 // No destinations applied.
1059 return this.transferAlert.open();
1062 this.transferHoldings.targetRecId = recId;
1063 this.transferHoldings.targetOrgId = orgId;
1064 this.transferHoldings.callNums = callNums;
1066 this.transferHoldings.transferHoldings()
1067 .then(success => success ? this.hardRefresh() : null);