1 import {Component, OnInit, Input, ViewChild, ViewEncapsulation
2 } from '@angular/core';
3 import {Router} from '@angular/router';
4 import {Observable, Observer, of} 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 {ReplaceBarcodeDialogComponent
27 } from '@eg/staff/share/holdings/replace-barcode-dialog.component';
28 import {DeleteHoldingDialogComponent
29 } from '@eg/staff/share/holdings/delete-volcopy-dialog.component';
30 import {BucketDialogComponent
31 } from '@eg/staff/share/buckets/bucket-dialog.component';
32 import {ConjoinedItemsDialogComponent
33 } from '@eg/staff/share/holdings/conjoined-items-dialog.component';
34 import {MakeBookableDialogComponent
35 } from '@eg/staff/share/booking/make-bookable-dialog.component';
36 import {TransferItemsComponent
37 } from '@eg/staff/share/holdings/transfer-items.component';
38 import {TransferHoldingsComponent
39 } from '@eg/staff/share/holdings/transfer-holdings.component';
40 import {AlertDialogComponent} from '@eg/share/dialog/alert.component';
41 import {BroadcastService} from '@eg/share/util/broadcast.service';
44 // The holdings grid models a single HoldingsTree, composed of HoldingsTreeNodes
45 // flattened on-demand into a list of HoldingEntry objects.
46 export class HoldingsTreeNode {
47 children: HoldingsTreeNode[];
48 nodeType: 'org' | 'callNum' | 'copy';
50 parentNode: HoldingsTreeNode;
60 root: HoldingsTreeNode;
62 this.root = new HoldingsTreeNode();
66 export class HoldingsEntry {
68 // org unit shortname, call number label, or copy barcode
69 locationLabel: string;
70 // location label indentation depth
71 locationDepth: number | null;
72 callNumCount: number | null;
73 copyCount: number | null;
74 callNumberLabel: string;
78 treeNode: HoldingsTreeNode;
82 selector: 'eg-holdings-maintenance',
83 templateUrl: 'holdings.component.html',
84 styleUrls: ['holdings.component.css'],
85 encapsulation: ViewEncapsulation.None
87 export class HoldingsMaintenanceComponent implements OnInit {
90 gridDataSource: GridDataSource;
91 gridTemplateContext: any;
92 @ViewChild('holdingsGrid', { static: true }) holdingsGrid: GridComponent;
94 // Manage visibility of various sub-sections
95 @ViewChild('callNumsCheckbox', { static: true })
96 private callNumsCheckbox: GridToolbarCheckboxComponent;
97 @ViewChild('copiesCheckbox', { static: true })
98 private copiesCheckbox: GridToolbarCheckboxComponent;
99 @ViewChild('emptyCallNumsCheckbox', { static: true })
100 private emptyCallNumsCheckbox: GridToolbarCheckboxComponent;
101 @ViewChild('emptyLibsCheckbox', { static: true })
102 private emptyLibsCheckbox: GridToolbarCheckboxComponent;
103 @ViewChild('markDamagedDialog', { static: true })
104 private markDamagedDialog: MarkDamagedDialogComponent;
105 @ViewChild('markMissingDialog', { static: true })
106 private markMissingDialog: MarkMissingDialogComponent;
107 @ViewChild('copyAlertsDialog', { static: true })
108 private copyAlertsDialog: CopyAlertsDialogComponent;
109 @ViewChild('replaceBarcode', { static: true })
110 private replaceBarcode: ReplaceBarcodeDialogComponent;
111 @ViewChild('deleteHolding', { static: true })
112 private deleteHolding: DeleteHoldingDialogComponent;
113 @ViewChild('bucketDialog', { static: true })
114 private bucketDialog: BucketDialogComponent;
115 @ViewChild('conjoinedDialog', { static: true })
116 private conjoinedDialog: ConjoinedItemsDialogComponent;
117 @ViewChild('makeBookableDialog', { static: true })
118 private makeBookableDialog: MakeBookableDialogComponent;
119 @ViewChild('transferItems', {static: false})
120 private transferItems: TransferItemsComponent;
121 @ViewChild('transferHoldings', {static: false})
122 private transferHoldings: TransferHoldingsComponent;
123 @ViewChild('transferAlert', {static: false})
124 private transferAlert: AlertDialogComponent;
126 holdingsTree: HoldingsTree;
128 // nodeType => id => tree node cache
129 treeNodeCache: {[nodeType: string]: {[id: number]: HoldingsTreeNode}};
131 // When true and a grid reload is called, the holdings data will be
132 // re-fetched from the server.
133 refreshHoldings: boolean;
135 // Used as a row identifier in th grid, since we're mixing object types.
138 // List of copies whose due date we need to retrieve.
139 itemCircsNeeded: IdlObject[];
141 // When true draw the grid based on the stored preferences.
142 // When not true, render based on the current "expanded" state of each node.
143 // Rendering from prefs happens on initial load and when any prefs change.
144 renderFromPrefs: boolean;
146 rowClassCallback: (row: any) => string;
147 cellTextGenerator: GridCellTextGenerator;
149 private _recId: number;
150 @Input() set recordId(id: number) {
152 // Only force new data collection when recordId()
153 // is invoked after ngInit() has already run.
158 get recordId(): number {
162 contextOrg: IdlObject;
165 private router: Router,
166 private org: OrgService,
167 private idl: IdlService,
168 private pcrud: PcrudService,
169 private auth: AuthService,
170 private staffCat: StaffCatalogService,
171 private store: ServerStoreService,
172 private localStore: StoreService,
173 private holdings: HoldingsService,
174 private broadcaster: BroadcastService,
175 private anonCache: AnonCacheService
177 // Set some sane defaults before settings are loaded.
178 this.gridDataSource = new GridDataSource();
179 this.refreshHoldings = true;
180 this.renderFromPrefs = true;
182 // TODO: need a separate setting for this?
183 this.contextOrg = this.staffCat.searchContext.searchOrg;
185 this.rowClassCallback = (row: any): string => {
188 return 'holdings-copy-row';
190 return 'holdings-callNum-row';
193 // Add a generic org unit class and a depth-specific
194 // class for styling different levels of the org tree.
195 return 'holdings-org-row holdings-org-row-' +
196 row.treeNode.target.ou_type().depth();
200 // Text-ify function for cells that use display templates.
201 this.cellTextGenerator = {
202 owner_label: row => row.locationLabel,
203 holdable: row => row.copy ?
204 this.gridTemplateContext.copyIsHoldable(row.copy) : ''
207 this.gridTemplateContext = {
208 toggleExpandRow: (row: HoldingsEntry) => {
209 row.treeNode.expanded = !row.treeNode.expanded;
211 if (!row.treeNode.expanded) {
212 // When collapsing a node, all child nodes should be
213 // collapsed as well.
214 const traverse = (node: HoldingsTreeNode) => {
215 node.expanded = false;
216 node.children.forEach(traverse);
218 traverse(row.treeNode);
221 this.holdingsGrid.reload();
224 copyIsHoldable: (copy: IdlObject): boolean => {
225 return copy.holdable() === 't'
226 && copy.location().holdable() === 't'
227 && copy.status().holdable() === 't';
233 this.initDone = true;
235 this.broadcaster.listen('eg.holdings.update').subscribe(data => {
236 if (data && data.records && data.records.includes(this.recordId)) {
237 this.refreshHoldings = true;
238 this.holdingsGrid.reload();
242 // These are pre-cached via the catalog resolver.
243 const settings = this.store.getItemBatchCached([
244 'cat.holdings_show_empty_org',
245 'cat.holdings_show_empty',
246 'cat.holdings_show_copies',
247 'cat.holdings_show_vols'
250 // Show call numbers by default when no preference is set.
251 let showCallNums = settings['cat.holdings_show_vols'];
252 if (showCallNums === null) { showCallNums = true; }
254 this.callNumsCheckbox.checked(showCallNums);
255 this.copiesCheckbox.checked(settings['cat.holdings_show_copies']);
256 this.emptyCallNumsCheckbox.checked(settings['cat.holdings_show_empty']);
257 this.emptyLibsCheckbox.checked(settings['cat.holdings_show_empty_org']);
259 this.initHoldingsTree();
260 this.gridDataSource.getRows = (pager: Pager, sort: any[]) => {
261 return this.fetchHoldings(pager);
265 contextOrgChanged(org: IdlObject) {
266 this.contextOrg = org;
271 this.renderFromPrefs = true;
272 this.refreshHoldings = true;
273 this.initHoldingsTree();
274 this.holdingsGrid.reload();
277 toggleShowCopies(value: boolean) {
278 this.store.setItem('cat.holdings_show_copies', value);
280 // Showing copies implies showing call numbers
281 this.callNumsCheckbox.checked(true);
283 this.renderFromPrefs = true;
284 this.holdingsGrid.reload();
287 toggleShowCallNums(value: boolean) {
288 this.store.setItem('cat.holdings_show_vols', value);
290 // Hiding call numbers implies hiding empty call numbers and copies.
291 this.copiesCheckbox.checked(false);
292 this.emptyCallNumsCheckbox.checked(false);
294 this.renderFromPrefs = true;
295 this.holdingsGrid.reload();
298 toggleShowEmptyCallNums(value: boolean) {
299 this.store.setItem('cat.holdings_show_empty', value);
301 this.callNumsCheckbox.checked(true);
303 this.renderFromPrefs = true;
304 this.holdingsGrid.reload();
307 toggleShowEmptyLibs(value: boolean) {
308 this.store.setItem('cat.holdings_show_empty_org', value);
309 this.renderFromPrefs = true;
310 this.holdingsGrid.reload();
313 onRowActivate(row: any) {
315 // Launch copy editor?
317 this.gridTemplateContext.toggleExpandRow(row);
323 const visibleOrgs = this.org.fullPath(this.contextOrg, true);
325 // The initial tree simply matches the org unit tree
326 const traverseOrg = (node: HoldingsTreeNode) => {
327 node.target.children().forEach((org: IdlObject) => {
328 if (visibleOrgs.indexOf(org.id()) === -1) {
329 return; // Org is outside of scope
331 const nodeChild = new HoldingsTreeNode();
332 nodeChild.nodeType = 'org';
333 nodeChild.target = org;
334 nodeChild.parentNode = node;
335 node.children.push(nodeChild);
336 this.treeNodeCache.org[org.id()] = nodeChild;
337 traverseOrg(nodeChild);
341 this.treeNodeCache = {
347 this.holdingsTree = new HoldingsTree();
348 this.holdingsTree.root.nodeType = 'org';
349 this.holdingsTree.root.target = this.org.root();
350 this.treeNodeCache.org[this.org.root().id()] = this.holdingsTree.root;
352 traverseOrg(this.holdingsTree.root);
355 // Org node children are sorted with any child org nodes pushed to the
356 // front, followed by the call number nodes sorted alphabetcially by label.
357 sortOrgNodeChildren(node: HoldingsTreeNode) {
358 node.children = node.children.sort((a, b) => {
359 if (a.nodeType === 'org') {
360 if (b.nodeType === 'org') {
361 return a.target.shortname() < b.target.shortname() ? -1 : 1;
365 } else if (b.nodeType === 'org') {
368 // TODO: should this use label sortkey instead of
369 // the compiled call number label?
370 return a.target._label < b.target._label ? -1 : 1;
375 // Sets call number and copy count sums to nodes that need it.
376 // Applies the initial expansed state of each container node.
377 setTreeCounts(node: HoldingsTreeNode) {
379 if (node.nodeType === 'org') {
381 node.callNumCount = 0;
382 } else if (node.nodeType === 'callNum') {
386 let hasChildOrgWithData = false;
387 let hasChildOrgSansData = false;
388 node.children.forEach(child => {
389 this.setTreeCounts(child);
390 if (node.nodeType === 'org') {
391 node.copyCount += child.copyCount;
392 if (child.nodeType === 'callNum') {
395 hasChildOrgWithData = child.callNumCount > 0;
396 hasChildOrgSansData = child.callNumCount === 0;
397 node.callNumCount += child.callNumCount;
399 } else if (node.nodeType === 'callNum') {
400 node.copyCount = node.children.length;
401 if (this.renderFromPrefs) {
402 node.expanded = this.copiesCheckbox.checked();
407 if (this.renderFromPrefs && node.nodeType === 'org') {
408 if (node.copyCount > 0 && this.callNumsCheckbox.checked()) {
409 node.expanded = true;
410 } else if (node.callNumCount > 0 && this.emptyCallNumsCheckbox.checked()) {
411 node.expanded = true;
412 } else if (hasChildOrgWithData) {
413 node.expanded = true;
414 } else if (hasChildOrgSansData && this.emptyLibsCheckbox.checked()) {
415 node.expanded = true;
417 node.expanded = false;
422 // Create HoldingsEntry objects for tree nodes that should be displayed
423 // and relays them to the grid via the observer.
424 propagateTreeEntries(observer: Observer<HoldingsEntry>, node: HoldingsTreeNode) {
425 const entry = new HoldingsEntry();
426 entry.treeNode = node;
427 entry.index = this.gridIndex++;
429 switch (node.nodeType) {
431 if (node.callNumCount === 0
432 && !this.emptyLibsCheckbox.checked()) {
435 entry.locationLabel = node.target.shortname();
436 entry.locationDepth = node.target.ou_type().depth();
437 entry.copyCount = node.copyCount;
438 entry.callNumCount = node.callNumCount;
439 this.sortOrgNodeChildren(node);
443 if (this.renderFromPrefs) {
444 if (!this.callNumsCheckbox.checked()) {
447 if (node.copyCount === 0
448 && !this.emptyCallNumsCheckbox.checked()) {
452 entry.locationLabel = node.target._label;
453 entry.locationDepth = node.parentNode.target.ou_type().depth() + 1;
454 entry.callNumberLabel = entry.locationLabel;
455 entry.callNum = node.target;
456 entry.copyCount = node.copyCount;
460 entry.locationLabel = node.target.barcode();
461 entry.locationDepth = node.parentNode.parentNode.target.ou_type().depth() + 2;
462 entry.callNumberLabel = node.parentNode.target.label(); // TODO
463 entry.callNum = node.parentNode.target;
464 entry.copy = node.target;
465 entry.circ = node.target._circ;
469 // Tell the grid about the node entry
470 observer.next(entry);
473 // Process the child nodes.
474 node.children.forEach(child =>
475 this.propagateTreeEntries(observer, child));
479 // Turns the tree into a list of entries for grid display
480 flattenHoldingsTree(observer: Observer<HoldingsEntry>) {
482 this.setTreeCounts(this.holdingsTree.root);
483 this.propagateTreeEntries(observer, this.holdingsTree.root);
485 this.renderFromPrefs = false;
488 // Grab call numbers, copies, and related data.
489 fetchHoldings(pager: Pager): Observable<any> {
490 if (!this.recordId) { return of([]); }
492 return new Observable<any>(observer => {
494 if (!this.refreshHoldings) {
495 this.flattenHoldingsTree(observer);
499 this.itemCircsNeeded = [];
501 this.pcrud.search('acn',
502 { record: this.recordId,
503 owning_lib: this.org.fullPath(this.contextOrg, true),
505 label: {'!=' : '##URI##'}
509 acp: ['status', 'location', 'circ_lib', 'parts',
510 'age_protect', 'copy_alerts', 'latest_inventory'],
511 acn: ['prefix', 'suffix', 'copies'],
512 acli: ['inventory_workstation']
515 {authoritative: true}
517 callNum => this.appendCallNum(callNum),
520 this.refreshHoldings = false;
521 this.fetchCircs().then(
522 ok => this.flattenHoldingsTree(observer)
529 // Retrieve circulation objects for checked out items.
530 fetchCircs(): Promise<any> {
531 const copyIds = this.itemCircsNeeded.map(copy => copy.id());
532 if (copyIds.length === 0) { return Promise.resolve(); }
534 return this.pcrud.search('circ', {
535 target_copy: copyIds,
537 }).pipe(map(circ => {
538 const copy = this.itemCircsNeeded.filter(
539 c => Number(c.id()) === Number(circ.target_copy()))[0];
544 // Compile prefix + label + suffix into field callNum._label;
545 setCallNumLabel(callNum: IdlObject) {
546 const pfx = callNum.prefix() ? callNum.prefix().label() : '';
547 const sfx = callNum.suffix() ? callNum.suffix().label() : '';
548 callNum._label = pfx ? pfx + ' ' : '';
549 callNum._label += callNum.label();
550 callNum._label += sfx ? ' ' + sfx : '';
553 // Create the tree node for the call number if it doesn't already exist.
554 // Do the same for its linked copies.
555 appendCallNum(callNum: IdlObject) {
556 let callNumNode = this.treeNodeCache.callNum[callNum.id()];
557 this.setCallNumLabel(callNum);
560 const pNode = this.treeNodeCache.org[callNum.owning_lib()];
561 if (callNumNode.parentNode.target.id() !== pNode.target.id()) {
562 // Call number owning library changed. Un-link it from the
563 // previous org unit collection before adding to the new one.
565 callNumNode.parentNode = pNode;
566 callNumNode.parentNode.children.push(callNumNode);
569 callNumNode = new HoldingsTreeNode();
570 callNumNode.nodeType = 'callNum';
571 callNumNode.parentNode = this.treeNodeCache.org[callNum.owning_lib()];
572 callNumNode.parentNode.children.push(callNumNode);
573 this.treeNodeCache.callNum[callNum.id()] = callNumNode;
576 callNumNode.target = callNum;
579 .filter((copy: IdlObject) => (copy.deleted() !== 't'))
580 .sort((a: IdlObject, b: IdlObject) => a.barcode() < b.barcode() ? -1 : 1)
581 .forEach((copy: IdlObject) => this.appendCopy(callNumNode, copy));
584 // Find or create a copy node.
585 appendCopy(callNumNode: HoldingsTreeNode, copy: IdlObject) {
586 let copyNode = this.treeNodeCache.copy[copy.id()];
589 const oldParent = copyNode.parentNode;
590 if (oldParent.target.id() !== callNumNode.target.id()) {
591 // TODO: copy changed owning call number. Remove it from
592 // the previous call number before adding to the new call number.
593 copyNode.parentNode = callNumNode;
594 callNumNode.children.push(copyNode);
598 copyNode = new HoldingsTreeNode();
599 copyNode.nodeType = 'copy';
600 callNumNode.children.push(copyNode);
601 copyNode.parentNode = callNumNode;
602 this.treeNodeCache.copy[copy.id()] = copyNode;
605 copyNode.target = copy;
606 const stat = Number(copy.status().id());
608 if (stat === 1 /* checked out */ || stat === 16 /* long overdue */) {
609 // Avoid looking up circs on items that are not checked out.
610 this.itemCircsNeeded.push(copy);
614 // Which copies in the grid are selected.
615 selectedCopyIds(rows: HoldingsEntry[], skipStatus?: number): number[] {
616 return this.selectedCopies(rows, skipStatus).map(c => Number(c.id()));
619 selectedVolIds(rows: HoldingsEntry[]): number[] {
621 .filter(r => Boolean(r.callNum))
622 .map(r => Number(r.callNum.id()));
625 selectedCopies(rows: HoldingsEntry[], skipStatus?: number): IdlObject[] {
626 let copyRows = rows.filter(r => Boolean(r.copy)).map(r => r.copy);
628 copyRows = copyRows.filter(
629 c => Number(c.status().id()) !== Number(skipStatus));
634 selectedCallNumIds(rows: HoldingsEntry[]): number[] {
635 return this.selectedCallNums(rows).map(cn => cn.id());
638 selectedCallNums(rows: HoldingsEntry[]): IdlObject[] {
640 .filter(r => r.treeNode.nodeType === 'callNum')
641 .map(r => r.callNum);
645 async showMarkDamagedDialog(rows: HoldingsEntry[]) {
646 const copyIds = this.selectedCopyIds(rows, 14 /* ignore damaged */);
648 if (copyIds.length === 0) { return; }
650 let rowsModified = false;
652 const markNext = async(ids: number[]) => {
653 if (ids.length === 0) {
654 return Promise.resolve();
657 this.markDamagedDialog.copyId = ids.pop();
658 return this.markDamagedDialog.open({size: 'lg'}).subscribe(
660 if (ok) { rowsModified = true; }
661 return markNext(ids);
663 dismiss => markNext(ids)
667 await markNext(copyIds);
669 this.refreshHoldings = true;
670 this.holdingsGrid.reload();
674 showMarkMissingDialog(rows: any[]) {
675 const copyIds = this.selectedCopyIds(rows, 4 /* ignore missing */);
676 if (copyIds.length > 0) {
677 this.markMissingDialog.copyIds = copyIds;
678 this.markMissingDialog.open({}).subscribe(
681 this.refreshHoldings = true;
682 this.holdingsGrid.reload();
685 dismissed => {} // avoid console errors
690 // Mark record, library, and potentially the selected call number
691 // as the current transfer target.
692 markLibCnForTransfer(rows: HoldingsEntry[]) {
693 if (rows.length === 0) {
697 // Action may only apply to a single org or call number row.
698 const node = rows[0].treeNode;
699 if (node.nodeType === 'copy') { return; }
703 if (node.nodeType === 'org') {
704 orgId = node.target.id();
706 // Clear call number target when performed on an org unit row
707 this.localStore.removeLocalItem('eg.cat.transfer_target_vol');
709 } else if (node.nodeType === 'callNum') {
711 // All call number nodes are children of org nodes.
712 orgId = node.parentNode.target.id();
714 // Add call number target when performed on a call number row.
715 this.localStore.setLocalItem(
716 'eg.cat.transfer_target_vol', node.target.id());
719 // Track lib and record to support transfering items from
720 // a different bib record to this record at the selected
722 this.localStore.setLocalItem('eg.cat.transfer_target_lib', orgId);
723 this.localStore.setLocalItem('eg.cat.transfer_target_record', this.recordId);
726 openAngJsWindow(path: string) {
727 const url = `/eg/staff/${path}`;
728 window.open(url, '_blank');
731 openItemHolds(rows: HoldingsEntry[]) {
732 if (rows.length > 0 && rows[0].copy) {
733 this.openAngJsWindow(`cat/item/${rows[0].copy.id()}/holds`);
737 openItemStatusList(rows: HoldingsEntry[]) {
738 const ids = this.selectedCopyIds(rows);
739 if (ids.length > 0) {
740 return this.openAngJsWindow(`cat/item/search/${ids.join(',')}`);
744 openItemStatus(rows: HoldingsEntry[]) {
745 if (rows.length > 0 && rows[0].copy) {
746 return this.openAngJsWindow(`cat/item/${rows[0].copy.id()}`);
750 openItemTriggeredEvents(rows: HoldingsEntry[]) {
751 if (rows.length > 0 && rows[0].copy) {
752 return this.openAngJsWindow(
753 `cat/item/${rows[0].copy.id()}/triggered_events`);
757 openItemPrintLabels(rows: HoldingsEntry[]) {
758 const ids = this.selectedCopyIds(rows);
759 if (ids.length === 0) { return; }
761 this.anonCache.setItem(null, 'print-labels-these-copies', {copies: ids})
762 .then(key => this.openAngJsWindow(`cat/printlabels/${key}`));
765 openHoldingEdit(rows: HoldingsEntry[], hideVols: boolean, hideCopies: boolean) {
767 // Avoid adding call number edit entries for call numbers
768 // that are already represented by selected items.
770 const copies = this.selectedCopies(rows);
771 const copyVols = copies.map(c => Number(c.call_number()));
774 this.selectedVolIds(rows).forEach(id => {
775 if (!copyVols.includes(id)) {
780 this.holdings.spawnAddHoldingsUi(
784 copies.map(c => Number(c.id())),
790 openHoldingAdd(rows: HoldingsEntry[], addCallNums: boolean, addCopies: boolean) {
792 // The user may select a set of call numbers by selecting call
793 // number and/or item rows. Owning libs for new call numbers may
794 // also come from org unit row selection.
798 if (r.treeNode.nodeType === 'callNum') {
799 callNums.push(r.callNum);
801 } else if (r.treeNode.nodeType === 'copy') {
802 callNums.push(r.treeNode.parentNode.target);
804 } else if (r.treeNode.nodeType === 'org') {
805 const org = r.treeNode.target;
806 if (org.ou_type().can_have_vols() === 't') {
807 orgs[org.id()] = true;
812 if (addCopies && !addCallNums) {
813 // Adding copies to an existing set of call numbers.
814 if (callNums.length > 0) {
815 const callNumIds = callNums.map(v => Number(v.id()));
816 this.holdings.spawnAddHoldingsUi(this.recordId, callNumIds);
819 } else if (addCallNums) {
822 // Use selected call numbers as basis for new call numbers.
823 callNums.forEach(v =>
824 entries.push({label: v.label(), owner: v.owning_lib()}));
826 // Use selected org units as owning libs for new call numbers
827 Object.keys(orgs).forEach(id => entries.push({owner: id}));
829 if (entries.length === 0) {
830 // Otherwise create new call numbers for "here"
831 entries.push({owner: this.auth.user().ws_ou()});
834 this.holdings.spawnAddHoldingsUi(
835 this.recordId, null, entries, null, !addCopies);
839 openItemNotes(rows: HoldingsEntry[], mode: string) {
840 const copyIds = this.selectedCopyIds(rows);
841 if (copyIds.length === 0) { return; }
843 this.copyAlertsDialog.copyIds = copyIds;
844 this.copyAlertsDialog.mode = mode;
845 this.copyAlertsDialog.open({size: 'lg'}).subscribe(
854 openReplaceBarcodeDialog(rows: HoldingsEntry[]) {
855 const ids = this.selectedCopyIds(rows);
856 if (ids.length === 0) { return; }
857 this.replaceBarcode.copyIds = ids;
858 this.replaceBarcode.open({}).subscribe(
867 // mode 'callNums' -- only delete empty call numbers
868 // mode 'copies' -- only delete selected copies
869 // mode 'both' -- delete selected copies and selected call numbers, plus all
870 // copies linked to selected call numbers, regardless of whether they are selected.
871 deleteHoldings(rows: HoldingsEntry[], mode: 'callNums' | 'copies' | 'both') {
872 const callNumHash: any = {};
874 if (mode === 'callNums' || mode === 'both') {
875 // Collect the call numbers to be deleted.
876 rows.filter(r => r.treeNode.nodeType === 'callNum').forEach(r => {
877 const callNum = this.idl.clone(r.callNum);
878 if (mode === 'callNums') {
879 if (callNum.copies().length > 0) {
880 // cannot delete non-empty call number in this mode.
884 callNum.copies().forEach(c => c.isdeleted(true));
886 callNum.isdeleted(true);
887 callNumHash[callNum.id()] = callNum;
891 if (mode === 'copies' || mode === 'both') {
892 // Collect the copies to be deleted, including their call numbers
893 // since the API expects fleshed call number objects.
894 rows.filter(r => r.treeNode.nodeType === 'copy').forEach(r => {
895 const callNum = r.treeNode.parentNode.target;
896 if (!callNumHash[callNum.id()]) {
897 callNumHash[callNum.id()] = this.idl.clone(callNum);
898 callNumHash[callNum.id()].copies([]);
900 const copy = this.idl.clone(r.copy);
901 copy.isdeleted(true);
902 callNumHash[callNum.id()].copies().push(copy);
906 if (Object.keys(callNumHash).length === 0) {
907 // No data to process.
911 // Note forceDeleteCopies should not be necessary here, since we
912 // manually marked all copies as deleted on deleted call numbers in
914 this.deleteHolding.forceDeleteCopies = mode === 'both';
915 this.deleteHolding.callNums = Object.values(callNumHash);
916 this.deleteHolding.open({size: 'sm'}).subscribe(
925 requestItems(rows: HoldingsEntry[]) {
926 const copyIds = this.selectedCopyIds(rows);
927 if (copyIds.length === 0) { return; }
928 const params = {target: copyIds, holdFor: 'staff'};
929 this.router.navigate(['/staff/catalog/hold/C'], {queryParams: params});
932 openBucketDialog(rows: HoldingsEntry[]) {
933 const copyIds = this.selectedCopyIds(rows);
934 if (copyIds.length > 0) {
935 this.bucketDialog.bucketClass = 'copy';
936 this.bucketDialog.itemIds = copyIds;
937 this.bucketDialog.open({size: 'lg'});
941 openConjoinedDialog(rows: HoldingsEntry[]) {
942 const copyIds = this.selectedCopyIds(rows);
943 if (copyIds.length > 0) {
944 this.conjoinedDialog.copyIds = copyIds;
945 this.conjoinedDialog.open({size: 'sm'});
949 bookItems(rows: HoldingsEntry[]) {
950 const copyIds = this.selectedCopyIds(rows);
951 if (copyIds.length > 0) {
952 this.router.navigate(
953 ['staff', 'booking', 'create_reservation', 'for_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
958 makeBookable(rows: HoldingsEntry[]) {
959 const copyIds = this.selectedCopyIds(rows);
960 if (copyIds.length > 0) {
961 this.makeBookableDialog.copyIds = copyIds;
962 this.makeBookableDialog.open({});
966 manageReservations(rows: HoldingsEntry[]) {
967 const copyIds = this.selectedCopyIds(rows);
968 if (copyIds.length > 0) {
969 this.router.navigate(
970 ['staff', 'booking', 'manage_reservations', 'by_resource', rows.filter(r => Boolean(r.copy))[0].copy.barcode()]
975 transferSelectedItems(rows: HoldingsEntry[]) {
976 if (rows.length === 0) { return; }
979 this.localStore.getLocalItem('eg.cat.transfer_target_vol');
982 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
985 this.localStore.getLocalItem('eg.cat.transfer_target_record');
989 if (cnId) { // Direct call number transfer
991 const itemIds = this.selectedCopyIds(rows);
992 promise = this.transferItems.transferItems(itemIds, cnId);
994 } else if (orgId && recId) { // "Auto" transfer
996 // Clone the items to be modified to avoid any unexpected
997 // modifications and fesh the call numbers.
998 const items = this.idl.clone(this.selectedCopies(rows));
999 items.forEach(i => i.call_number(
1000 this.treeNodeCache.callNum[i.call_number()].target));
1003 promise = this.transferItems.autoTransferItems(items, recId, orgId);
1006 promise = this.transferAlert.open().toPromise();
1009 promise.then(success => success ? this.hardRefresh() : null);
1012 transferSelectedHoldings(rows: HoldingsEntry[]) {
1013 const callNums = this.selectedCallNums(rows);
1014 if (callNums.length === 0) { return; }
1017 this.localStore.getLocalItem('eg.cat.transfer_target_lib');
1020 this.localStore.getLocalItem('eg.cat.transfer_target_record');
1023 // When transferring holdings (call numbers) between org units,
1024 // limit transfers to within the current record.
1025 recId = this.recordId;
1027 } else if (!recId) {
1028 // No destinations applied.
1029 return this.transferAlert.open();
1032 this.transferHoldings.targetRecId = recId;
1033 this.transferHoldings.targetOrgId = orgId;
1034 this.transferHoldings.callNums = callNums;
1036 this.transferHoldings.transferHoldings()
1037 .then(success => success ? this.hardRefresh() : null);