]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/item/app.js
LP1821196: Remove arrow function from item status
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / item / app.js
1 /**
2  * Item Display
3  */
4
5 angular.module('egItemStatus', 
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod'])
7
8 .filter('boolText', function(){
9     return function (v) {
10         return v == 't';
11     }
12 })
13
14 .config(function($routeProvider, $locationProvider, $compileProvider) {
15     $locationProvider.html5Mode(true);
16     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
17         
18     var resolver = {delay : function(egStartup) {return egStartup.go()}};
19
20     // search page shows the list view by default
21     $routeProvider.when('/cat/item/search', {
22         templateUrl: './cat/item/t_list',
23         controller: 'ListCtrl',
24         resolve : resolver
25     });
26
27     // search page shows the list view by default
28     $routeProvider.when('/cat/item/search/:idList', {
29         templateUrl: './cat/item/t_list',
30         controller: 'ListCtrl',
31         resolve : resolver
32     });
33
34     $routeProvider.when('/cat/item/:id', {
35         templateUrl: './cat/item/t_view',
36         controller: 'ViewCtrl',
37         resolve : resolver
38     });
39
40     $routeProvider.when('/cat/item/:id/:tab', {
41         templateUrl: './cat/item/t_view',
42         controller: 'ViewCtrl',
43         resolve : resolver
44     });
45
46     // default page / bucket view
47     $routeProvider.otherwise({redirectTo : '/cat/item/search'});
48 })
49
50 /**
51  * Search bar along the top of the page.
52  * Parent scope for list and detail views
53  */
54 .controller('SearchCtrl', 
55        ['$scope','$q','$window','$location','$timeout','egCore','egNet','egGridDataProvider','egItem',
56 function($scope , $q , $window , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc) {
57     $scope.args = {}; // search args
58
59     // sub-scopes (search / detail-view) apply their version 
60     // of retrieval function to $scope.context.search
61     // and display toggling via $scope.context.toggleDisplay
62     $scope.context = {
63         selectBarcode : true
64     };
65
66     $scope.toggleView = function($event) {
67         $scope.context.toggleDisplay();
68         $event.preventDefault(); // avoid form submission
69     }
70
71     // The functions that follow in this controller are never called
72     // when the List View is active, only the Detail View.
73     
74     // In this context, we're only ever dealing with 1 item, so
75     // we can simply refresh the page.  These various itemSvc
76     // functions used to live in the ListCtrl, but they're now
77     // shared between SearchCtrl (for Actions for the Detail View)
78     // and ListCtrl (Actions in the egGrid)
79     itemSvc.add_barcode_to_list = function(b) {
80         //console.log('SearchCtrl: add_barcode_to_list',b);
81         // timeout so audible can happen upon checkin
82         $timeout(function() { location.href = location.href; }, 1000);
83     }
84
85     $scope.add_copies_to_bucket = function() {
86         itemSvc.add_copies_to_bucket([$scope.args.copyId]);
87     }
88
89     $scope.make_copies_bookable = function() {
90         itemSvc.make_copies_bookable([{
91             id : $scope.args.copyId,
92             'call_number.record.id' : $scope.args.recordId
93         }]);
94     }
95
96     $scope.book_copies_now = function() {
97         itemSvc.book_copies_now([{
98             id : $scope.args.copyId,
99             'call_number.record.id' : $scope.args.recordId
100         }]);
101     }
102
103     $scope.findAcquisition = function() {
104         var acqData;
105         var promises = [];
106         $scope.openAcquisitionLineItem([$scope.args.copyId]);
107     }
108
109     $scope.openAcquisitionLineItem = function (cp_list) {
110         var hasResults = false;
111         var promises = [];
112
113         angular.forEach(cp_list, function (copyId) {
114             promises.push(
115                 egNet.request(
116                     'open-ils.acq',
117                     'open-ils.acq.lineitem.retrieve.by_copy_id',
118                     egCore.auth.token(),
119                     copyId
120                 ).then(function (acqData) {
121                     if (acqData) {
122                         if (acqData.a) {
123                             acqData = egCore.idl.toHash(acqData);
124                             var url = '/eg/acq/po/view/' + acqData.purchase_order + '/' + acqData.id;
125                             $timeout(function () { $window.open(url, '_blank') });
126                             hasResults = true;
127                         }
128                     }
129                 })
130             )
131         });
132
133         $q.all(promises).then(function () {
134             !hasResults ? alert('There is no corresponding purchase order for this item.') : false;
135         });
136     }
137
138     $scope.requestItems = function() {
139         itemSvc.requestItems([$scope.args.copyId]);
140     }
141
142     $scope.update_inventory = function() {
143         itemSvc.updateInventory([$scope.args.copyId], null)
144         .then(function(res) {
145             $timeout(function() { location.href = location.href; }, 1000);
146         });
147     }
148
149     $scope.attach_to_peer_bib = function() {
150         itemSvc.attach_to_peer_bib([{
151             id : $scope.args.copyId,
152             barcode : $scope.args.copyBarcode
153         }]);
154     }
155
156     $scope.selectedHoldingsCopyDelete = function () {
157         itemSvc.selectedHoldingsCopyDelete([{
158             id : $scope.args.copyId,
159             barcode : $scope.args.copyBarcode
160         }]);
161     }
162
163     $scope.checkin = function () {
164         itemSvc.checkin([{
165             id : $scope.args.copyId,
166             barcode : $scope.args.copyBarcode
167         }]);
168     }
169
170     $scope.renew = function () {
171         itemSvc.renew([{
172             id : $scope.args.copyId,
173             barcode : $scope.args.copyBarcode
174         }]);
175     }
176
177     $scope.cancel_transit = function () {
178         itemSvc.cancel_transit([{
179             id : $scope.args.copyId,
180             barcode : $scope.args.copyBarcode
181         }]);
182     }
183
184     $scope.selectedHoldingsDamaged = function () {
185         itemSvc.selectedHoldingsDamaged([{
186             id : $scope.args.copyId,
187             barcode : $scope.args.copyBarcode,
188             refresh : true
189         }]);
190     }
191
192     $scope.selectedHoldingsMissing = function () {
193         itemSvc.selectedHoldingsMissing([{
194             id : $scope.args.copyId,
195             barcode : $scope.args.copyBarcode
196         }]);
197     }
198
199     $scope.selectedHoldingsVolCopyAdd = function () {
200         itemSvc.spawnHoldingsAdd([{
201             id : $scope.args.copyId,
202             'call_number.owning_lib' : $scope.args.cnOwningLib,
203             'call_number.record.id' : $scope.args.recordId,
204             barcode : $scope.args.copyBarcode
205         }],true,false);
206     }
207     $scope.selectedHoldingsCopyAdd = function () {
208         itemSvc.spawnHoldingsAdd([{
209             id : $scope.args.copyId,
210             'call_number.id' : $scope.args.cnId,
211             'call_number.owning_lib' : $scope.args.cnOwningLib,
212             'call_number.record.id' : $scope.args.recordId,
213             barcode : $scope.args.copyBarcode
214         }],false,true);
215     }
216
217     $scope.selectedHoldingsVolCopyEdit = function () {
218         itemSvc.spawnHoldingsEdit([{
219             id : $scope.args.copyId,
220             'call_number.id' : $scope.args.cnId,
221             'call_number.owning_lib' : $scope.args.cnOwningLib,
222             'call_number.record.id' : $scope.args.recordId,
223             barcode : $scope.args.copyBarcode
224         }],false,false);
225     }
226     $scope.selectedHoldingsVolEdit = function () {
227         itemSvc.spawnHoldingsEdit([{
228             id : $scope.args.copyId,
229             'call_number.id' : $scope.args.cnId,
230             'call_number.owning_lib' : $scope.args.cnOwningLib,
231             'call_number.record.id' : $scope.args.recordId,
232             barcode : $scope.args.copyBarcode
233         }],false,true);
234     }
235     $scope.selectedHoldingsCopyEdit = function () {
236         itemSvc.spawnHoldingsEdit([{
237             id : $scope.args.copyId,
238             'call_number.id' : $scope.args.cnId,
239             'call_number.owning_lib' : $scope.args.cnOwningLib,
240             'call_number.record.id' : $scope.args.recordId,
241             barcode : $scope.args.copyBarcode
242         }],true,false);
243     }
244
245     $scope.replaceBarcodes = function() {
246         itemSvc.replaceBarcodes([{
247             id : $scope.args.copyId,
248             barcode : $scope.args.copyBarcode
249         }]);
250     }
251
252     $scope.changeItemOwningLib = function() {
253         itemSvc.changeItemOwningLib([{
254             id : $scope.args.copyId,
255             'call_number.id' : $scope.args.cnId,
256             'call_number.owning_lib' : $scope.args.cnOwningLib,
257             'call_number.record.id' : $scope.args.recordId,
258             'call_number.label' : $scope.args.cnLabel,
259             'call_number.label_class' : $scope.args.cnLabelClass,
260             'call_number.prefix.id' : $scope.args.cnPrefixId,
261             'call_number.suffix.id' : $scope.args.cnSuffixId,
262             barcode : $scope.args.copyBarcode
263         }]);
264     }
265
266     $scope.transferItems = function (){
267         itemSvc.transferItems([{
268             id : $scope.args.copyId,
269             barcode : $scope.args.copyBarcode
270         }]);
271     }
272
273 }])
274
275 /**
276  * List view - grid stuff
277  */
278 .controller('ListCtrl', 
279        ['$scope','$q','$routeParams','$location','$timeout','$window','egCore',
280         'egGridDataProvider','egItem','egUser','$uibModal','egCirc','egConfirmDialog',
281         'egProgressDialog', 'ngToast',
282 // function($scope , $q , $routeParams , $location , $timeout , $window , egCore , 
283 //          egGridDataProvider , itemSvc , egUser , $uibModal , egCirc , egConfirmDialog,
284 //          egProgressDialog, ngToast) {
285     function($scope , $q , $routeParams , $location , $timeout , $window , egCore , egGridDataProvider , itemSvc , egUser , $uibModal , egCirc , egConfirmDialog,
286                  egProgressDialog, ngToast) {
287     var copyId = [];
288     var cp_list = $routeParams.idList;
289     if (cp_list) {
290         copyId = cp_list.split(',');
291     }
292
293     var modified_items = new Set();
294
295     $scope.context.page = 'list';
296
297     /*
298     var provider = egGridDataProvider.instance();
299     provider.get = function(offset, count) {
300     }
301     */
302
303     $scope.gridDataProvider = egGridDataProvider.instance({
304         get : function(offset, count) {
305             //return provider.arrayNotifier(itemSvc.copies, offset, count);
306             return this.arrayNotifier(itemSvc.copies, offset, count);
307         }
308     });
309
310     // If a copy was just displayed in the detail view, ensure it's
311     // focused in the list view.
312     var selected = false;
313     var copyGrid = $scope.gridControls = {
314         itemRetrieved : function(item) {
315             if (selected || !itemSvc.copy) return;
316             if (itemSvc.copy.id() == item.id) {
317                 copyGrid.selectItems([item.index]);
318                 selected = true;
319             }
320         }
321     };
322
323     $scope.$watch('barcodesFromFile', function(newVal, oldVal) {
324         if (newVal && newVal != oldVal) {
325             $scope.args.barcode = '';
326             var barcodes = [];
327
328             angular.forEach(newVal.split(/\n/), function(line) {
329                 if (!line) return;
330                 // scrub any trailing spaces or commas from the barcode
331                 line = line.replace(/(.*?)($|\s.*|,.*)/,'$1');
332                 barcodes.push(line);
333             });
334
335             // Serialize copy retrieval since there may be many, many copies.
336             function fetch_next_copy() {
337                 var barcode = barcodes.pop();
338                 egProgressDialog.increment();
339
340                 if (!barcode) { // All done here.
341                     egProgressDialog.close();
342                     copyGrid.refresh();
343                     copyGrid.selectItems([itemSvc.copies[0].index]);
344                     return;
345                 }
346
347                 itemSvc.fetch(barcode).then(fetch_next_copy);
348             }
349
350             if (barcodes.length) {
351                 egProgressDialog.open({value: 0, max: barcodes.length});
352                 fetch_next_copy();
353             }
354         }
355     });
356
357     $scope.context.search = function(args) {
358         if (!args.barcode) return;
359         $scope.context.itemNotFound = false;
360         itemSvc.fetch(args.barcode).then(function(res) {
361             if (res) {
362                 copyGrid.refresh();
363                 copyGrid.selectItems([res.index]);
364                 $scope.args.barcode = '';
365             } else {
366                 $scope.context.itemNotFound = true;
367                 egCore.audio.play('warning.item_status.itemNotFound');
368             }
369             $scope.context.selectBarcode = true;
370         })
371     }
372
373     var add_barcode_to_list = function (b) {
374         //console.log('listCtrl: add_barcode_to_list',b);
375         $scope.context.search({barcode:b});
376     }
377     itemSvc.add_barcode_to_list = add_barcode_to_list;
378
379     $scope.context.toggleDisplay = function() {
380         var item = copyGrid.selectedItems()[0];
381         if (item) 
382             $location.path('/cat/item/' + item.id);
383     }
384
385     $scope.context.show_triggered_events = function() {
386         var item = copyGrid.selectedItems()[0];
387         if (item) 
388             $location.path('/cat/item/' + item.id + '/triggered_events');
389     }
390
391     function gatherSelectedRecordIds () {
392         var rid_list = [];
393         angular.forEach(
394             copyGrid.selectedItems(),
395             function (item) {
396                 if (rid_list.indexOf(item['call_number.record.id']) == -1)
397                     rid_list.push(item['call_number.record.id'])
398             }
399         );
400         return rid_list;
401     }
402
403     function gatherSelectedVolumeIds (rid) {
404         var cn_id_list = [];
405         angular.forEach(
406             copyGrid.selectedItems(),
407             function (item) {
408                 if (rid && item['call_number.record.id'] != rid) return;
409                 if (cn_id_list.indexOf(item['call_number.id']) == -1)
410                     cn_id_list.push(item['call_number.id'])
411             }
412         );
413         return cn_id_list;
414     }
415
416     function gatherSelectedHoldingsIds (rid) {
417         var cp_id_list = [];
418         angular.forEach(
419             copyGrid.selectedItems(),
420             function (item) {
421                 if (rid && item['call_number.record.id'] != rid) return;
422                 cp_id_list.push(item.id)
423             }
424         );
425         return cp_id_list;
426     }
427
428     $scope.refreshGridData = function() {
429         var chain = $q.when();
430         var all_items = itemSvc.copies.map(function(item) {
431             return item.id;
432         });
433         angular.forEach(all_items.reverse(), function(i) {
434             itemSvc.copies.shift();
435             chain = chain.then(function() {
436                 return itemSvc.fetch(null, i);
437             });
438         });
439         return chain.then(function() {
440             copyGrid.refresh();
441         });
442     }
443
444
445     $scope.add_copies_to_bucket = function() {
446         var copy_list = gatherSelectedHoldingsIds();
447         itemSvc.add_copies_to_bucket(copy_list);
448     }
449
450     $scope.locateAcquisition = function() {
451         if (gatherSelectedHoldingsIds) {
452             var cp_list = gatherSelectedHoldingsIds();
453             if (cp_list) {
454                 if (cp_list.length > 0) {
455                     $scope.openAcquisitionLineItem(cp_list);
456                 }
457             }
458         }
459     }
460
461     $scope.update_inventory = function() {
462         var copy_list = gatherSelectedHoldingsIds();
463         itemSvc.updateInventory(copy_list, $scope.gridControls.allItems()).then(function(res) {
464             if (res) {
465                 $scope.gridControls.allItems(res);
466                 ngToast.create(egCore.strings.SUCCESS_UPDATE_INVENTORY);
467             } else {
468                 ngToast.warning(egCore.strings.FAIL_UPDATE_INVENTORY);
469             }
470         });
471     }
472
473     $scope.need_one_selected = function() {
474         var items = $scope.gridControls.selectedItems();
475         if (items.length == 1) return false;
476         return true;
477     };
478
479     $scope.make_copies_bookable = function() {
480         itemSvc.make_copies_bookable(copyGrid.selectedItems());
481     }
482
483     $scope.book_copies_now = function() {
484         itemSvc.book_copies_now(copyGrid.selectedItems());
485     }
486
487     $scope.requestItems = function() {
488         var copy_list = gatherSelectedHoldingsIds();
489         itemSvc.requestItems(copy_list);
490     }
491
492     $scope.replaceBarcodes = function() {
493         itemSvc.replaceBarcodes(copyGrid.selectedItems());
494     }
495
496     $scope.attach_to_peer_bib = function() {
497         itemSvc.attach_to_peer_bib(copyGrid.selectedItems());
498     }
499
500     $scope.selectedHoldingsCopyDelete = function () {
501         itemSvc.selectedHoldingsCopyDelete(copyGrid.selectedItems());
502     }
503
504     $scope.selectedHoldingsItemStatusTgrEvt= function() {
505         var item = copyGrid.selectedItems()[0];
506         if (item)
507             $location.path('/cat/item/' + item.id + '/triggered_events');
508     }
509
510     $scope.selectedHoldingsItemStatusHolds= function() {
511         var item = copyGrid.selectedItems()[0];
512         if (item)
513             $location.path('/cat/item/' + item.id + '/holds');
514     }
515
516     $scope.cancel_transit = function () {
517         itemSvc.cancel_transit(copyGrid.selectedItems());
518     }
519
520     $scope.selectedHoldingsDamaged = function () {
521         itemSvc.selectedHoldingsDamaged(copyGrid.selectedItems());
522     }
523
524     $scope.selectedHoldingsMissing = function () {
525         itemSvc.selectedHoldingsMissing(copyGrid.selectedItems());
526     }
527
528     $scope.checkin = function () {
529         itemSvc.checkin(copyGrid.selectedItems());
530     }
531
532     $scope.renew = function () {
533         itemSvc.renew(copyGrid.selectedItems());
534     }
535
536     $scope.selectedHoldingsVolCopyAdd = function () {
537         itemSvc.spawnHoldingsAdd(copyGrid.selectedItems(),true,false);
538     }
539     $scope.selectedHoldingsCopyAdd = function () {
540         itemSvc.spawnHoldingsAdd(copyGrid.selectedItems(),false,true);
541     }
542
543     $scope.selectedHoldingsCopyAlertsAdd = function(items) {
544         var copy_ids = [];
545         angular.forEach(items, function(item) {
546             if (item.id) copy_ids.push(item.id);
547         });
548         egCirc.add_copy_alerts(copy_ids).then(function() {
549             // update grid items?
550         });
551     }
552
553     $scope.selectedHoldingsCopyAlertsEdit = function(items) {
554         var copy_ids = [];
555         angular.forEach(items, function(item) {
556             if (item.id) copy_ids.push(item.id);
557         });
558         egCirc.manage_copy_alerts(copy_ids).then(function() {
559             // update grid items?
560         });
561     }
562
563     $scope.gridCellHandlers = {};
564     $scope.gridCellHandlers.copyAlertsEdit = function(id) {
565         egCirc.manage_copy_alerts([id]).then(function() {
566             // update grid items?
567         });
568     };
569
570     $scope.showBibHolds = function () {
571         angular.forEach(gatherSelectedRecordIds(), function (r) {
572             var url = egCore.env.basePath + 'cat/catalog/record/' + r + '/holds';
573             $timeout(function() { $window.open(url, '_blank') });
574         });
575     }
576
577     $scope.selectedHoldingsVolCopyEdit = function () {
578         itemSvc.spawnHoldingsEdit(copyGrid.selectedItems(),false,false);
579     }
580     $scope.selectedHoldingsVolEdit = function () {
581         itemSvc.spawnHoldingsEdit(copyGrid.selectedItems(),false,true);
582     }
583     $scope.selectedHoldingsCopyEdit = function () {
584         itemSvc.spawnHoldingsEdit(copyGrid.selectedItems(),true,false);
585     }
586
587     $scope.changeItemOwningLib = function() {
588         itemSvc.changeItemOwningLib(copyGrid.selectedItems());
589     }
590
591     $scope.transferItems = function (){
592         itemSvc.transferItems(copyGrid.selectedItems());
593     }
594
595     $scope.print_labels = function() {
596         egCore.net.request(
597             'open-ils.actor',
598             'open-ils.actor.anon_cache.set_value',
599             null, 'print-labels-these-copies', {
600                 copies : gatherSelectedHoldingsIds()
601             }
602         ).then(function(key) {
603             if (key) {
604                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
605                 $timeout(function() { $window.open(url, '_blank') });
606             } else {
607                 alert('Could not create anonymous cache key!');
608             }
609         });
610     }
611
612     $scope.print_list = function() {
613         var print_data = { copies : copyGrid.allItems() };
614
615         if (print_data.copies.length == 0) return $q.when();
616
617         return egCore.print.print({
618             template : 'item_status',
619             scope : print_data
620         });
621     }
622
623     $scope.show_in_catalog = function(){
624         itemSvc.show_in_catalog(copyGrid.selectedItems());
625     }
626
627     if (copyId.length > 0) {
628         var fetch_list = [];
629         angular.forEach(copyId, function (c) {
630             fetch_list.push(itemSvc.fetch(null,c));
631         });
632
633         return $q.all(fetch_list).then(function (res) { copyGrid.refresh(); });
634     }
635
636     $scope.statusIconColumn = {
637         isEnabled: true,
638         template:  function(item) {
639             var icon = '';
640             if (modified_items.has(item['id'])) {
641                 icon = '<span class="glyphicon glyphicon-floppy-saved"' +
642                     'title="' + egCore.strings.ITEM_SUCCESSFULLY_MODIFIED + '" ' +
643                     'aria-label="' + egCore.strings.ITEM_SUCCESSFULLY_MODIFIED + '">' +
644                     '</span>';
645             }
646             return icon
647         }
648     }
649
650     if (typeof BroadcastChannel != 'undefined') {
651         var holdings_bChannel = new BroadcastChannel("eg.holdings.update");
652         holdings_bChannel.onmessage = function(e) {
653             angular.forEach(e.data.copies, function(i) {
654                 modified_items.add(i);
655             });
656             ngToast.create(egCore.strings.ITEMS_SUCCESSFULLY_MODIFIED);
657             $scope.refreshGridData();
658         }
659         $scope.$on('$destroy', function() {
660             holdings_bChannel.close();
661         });
662     }
663
664 }])
665
666 /**
667  * Detail view -- shows one copy
668  */
669 .controller('ViewCtrl', 
670        ['$scope','$q','$location','$routeParams','$timeout','$window','egCore','egItem','egBilling','egCirc',
671 function($scope , $q , $location , $routeParams , $timeout , $window , egCore , itemSvc , egBilling , egCirc) {
672     var copyId = $routeParams.id;
673     $scope.args.copyId = copyId;
674     $scope.tab = $routeParams.tab || 'summary';
675     $scope.context.page = 'detail';
676     $scope.summaryRecord = null;
677
678     $scope.edit = false;
679     if ($scope.tab == 'edit') {
680         $scope.tab = 'summary';
681         $scope.edit = true;
682     }
683
684
685     // use the cached record info
686     if (itemSvc.copy) {
687         $scope.copy_alert_count = itemSvc.copy.copy_alerts().filter(function(aca) {
688             return !aca.ack_time();
689         }).length;
690         $scope.recordId = itemSvc.copy.call_number().record().id();
691         $scope.args.recordId = $scope.recordId;
692         $scope.args.cnId = itemSvc.copy.call_number().id();
693         $scope.args.cnOwningLib = itemSvc.copy.call_number().owning_lib();
694         $scope.args.cnLabel = itemSvc.copy.call_number().label();
695         $scope.args.cnLabelClass = itemSvc.copy.call_number().label_class();
696         $scope.args.cnPrefixId = itemSvc.copy.call_number().prefix().id();
697         $scope.args.cnSuffixId = itemSvc.copy.call_number().suffix().id();
698         $scope.args.copyBarcode = itemSvc.copy.barcode();
699     }
700
701     function loadCopy(barcode) {
702         $scope.context.itemNotFound = false;
703
704         // Avoid re-fetching the same copy while jumping tabs.
705         // In addition to being quicker, this helps to avoid flickering
706         // of the top panel which is always visible in the detail view.
707         //
708         // 'barcode' represents the loading of a new item - refetch it
709         // regardless of whether it matches the current item.
710         if (!barcode && itemSvc.copy && itemSvc.copy.id() == copyId) {
711             $scope.copy = itemSvc.copy;
712             if (itemSvc.latest_inventory && itemSvc.latest_inventory.copy() == copyId) {
713                 $scope.latest_inventory = itemSvc.latest_inventory;
714             }
715             $scope.copy_alert_count = itemSvc.copy.copy_alerts().filter(function(aca) {
716                 return !aca.ack_time();
717             }).length;
718             $scope.recordId = itemSvc.copy.call_number().record().id();
719             $scope.args.recordId = $scope.recordId;
720             $scope.args.cnId = itemSvc.copy.call_number().id();
721             $scope.args.cnOwningLib = itemSvc.copy.call_number().owning_lib();
722             $scope.args.cnLabel = itemSvc.copy.call_number().label();
723             $scope.args.cnLabelClass = itemSvc.copy.call_number().label_class();
724             $scope.args.cnPrefixId = itemSvc.copy.call_number().prefix().id();
725             $scope.args.cnSuffixId = itemSvc.copy.call_number().suffix().id();
726             $scope.args.copyBarcode = itemSvc.copy.barcode();
727             return $q.when();
728         }
729
730         delete $scope.copy;
731         delete itemSvc.copy;
732
733         var deferred = $q.defer();
734         itemSvc.fetch(barcode, copyId, true).then(function(res) {
735             $scope.context.selectBarcode = true;
736
737             if (!res) {
738                 copyId = null;
739                 $scope.context.itemNotFound = true;
740                 egCore.audio.play('warning.item_status.itemNotFound');
741                 deferred.reject(); // avoid propagation of data fetch calls
742                 return;
743             }
744
745             var copy = res.copy;
746             itemSvc.copy = copy;
747             if (res.latest_inventory) itemSvc.latest_inventory = res.latest_inventory;
748
749
750             $scope.copy = copy;
751             $scope.latest_inventory = res.latest_inventory;
752             $scope.copy_alert_count = copy.copy_alerts().filter(function(aca) {
753                 return !aca.ack_time();
754             }).length;
755 console.debug($scope.copy_alert_count);
756             $scope.recordId = copy.call_number().record().id();
757             $scope.args.recordId = $scope.recordId;
758             $scope.args.cnId = itemSvc.copy.call_number().id();
759             $scope.args.cnOwningLib = itemSvc.copy.call_number().owning_lib();
760             $scope.args.cnLabel = itemSvc.copy.call_number().label();
761             $scope.args.cnLabelClass = itemSvc.copy.call_number().label_class();
762             $scope.args.cnPrefixId = itemSvc.copy.call_number().prefix().id();
763             $scope.args.cnSuffixId = itemSvc.copy.call_number().suffix().id();
764             $scope.args.copyBarcode = copy.barcode();
765             $scope.args.barcode = '';
766
767             // locally flesh org units
768             copy.circ_lib(egCore.org.get(copy.circ_lib()));
769             copy.call_number().owning_lib(
770                 egCore.org.get(copy.call_number().owning_lib()));
771
772             var r = copy.call_number().record();
773             if (r.owner()) r.owner(egCore.org.get(r.owner())); 
774
775             // make boolean for auto-magic true/false display
776             angular.forEach(
777                 ['ref','opac_visible','holdable','circulate'],
778                 function(field) { copy[field](Boolean(copy[field]() == 't')) }
779             );
780
781             // finally, if this is a different copy, redirect.
782             // Note that we flesh first since the copy we just
783             // fetched will be used after the redirect.
784             if (copyId && copyId != copy.id()) {
785                 // if a new barcode is scanned in the detail view,
786                 // update the url to match the ID of the new copy
787                 $location.path('/cat/item/' + copy.id() + '/' + $scope.tab);
788                 deferred.reject(); // avoid propagation of data fetch calls
789                 return;
790             }
791             copyId = copy.id();
792
793             deferred.resolve();
794         });
795
796         return deferred.promise;
797     }
798
799     // load the two most recent circulations in /circs tab
800     function loadCurrentCirc() {
801         delete $scope.circ;
802         delete $scope.circ_summary;
803         delete $scope.prev_circ_summary;
804         delete $scope.prev_circ_usr;
805         if (!copyId) return;
806         
807         var copy_org =
808             itemSvc.copy.call_number().id() == -1 ?
809             itemSvc.copy.circ_lib().id() :
810             itemSvc.copy.call_number().owning_lib().id();
811
812         // since a user can still view patron checkout history here, check perms
813         egCore.perm.hasPermAt('VIEW_COPY_CHECKOUT_HISTORY', true)
814         .then(function(orgIds){
815             if(orgIds.indexOf(copy_org) == -1){
816                 console.warn('User is not allowed to view circ history!');
817                 $q.when(0);
818             }
819
820             return fetchMaxCircHistory();
821         })
822         .then(function(maxHistCount){
823
824             if (!maxHistCount) $scope.isMaxCircHistoryZero = true;
825
826             egCore.pcrud.search('aacs',
827                 {target_copy : copyId},
828                 {   flesh : 2,
829                     flesh_fields : {
830                         aacs : [
831                             'usr',
832                             'workstation',
833                             'checkin_workstation',
834                             'duration_rule',
835                             'max_fine_rule',
836                             'recurring_fine_rule'
837                         ],
838                         au : ['card']
839                     },
840                     order_by : {aacs : 'xact_start desc'},
841                     limit :  1
842                 }
843
844             ).then(null, null, function(circ) {
845                 $scope.circ = circ;
846
847                 if (!circ) return $q.when();
848
849                 // load the chain for this circ
850                 egCore.net.request(
851                     'open-ils.circ',
852                     'open-ils.circ.renewal_chain.retrieve_by_circ.summary',
853                     egCore.auth.token(), $scope.circ.id()
854                 ).then(function(summary) {
855                     $scope.circ_summary = summary;
856                 });
857
858                 if (maxHistCount <= 1) return;
859
860                 // load the chain for the previous circ, plus the user
861                 egCore.net.request(
862                     'open-ils.circ',
863                     'open-ils.circ.prev_renewal_chain.retrieve_by_circ.summary',
864                     egCore.auth.token(), $scope.circ.id()
865
866                 ).then(null, null, function(summary) {
867                     $scope.prev_circ_summary = summary.summary;
868
869                     if (summary.usr) { // aged circs have no 'usr'.
870                         egCore.pcrud.retrieve('au', summary.usr,
871                             {flesh : 1, flesh_fields : {au : ['card']}})
872
873                         .then(function(user) { $scope.prev_circ_usr = user });
874                     }
875                 });
876             });
877         })
878     }
879
880     var maxHistory;
881     function fetchMaxCircHistory() {
882         if (maxHistory) return $q.when(maxHistory);
883         return egCore.org.settings(
884             'circ.item_checkout_history.max')
885         .then(function(set) {
886             maxHistory = set['circ.item_checkout_history.max'] || 4;
887             return Number(maxHistory);
888         });
889     }
890
891     $scope.addBilling = function(circ) {
892         egBilling.showBillDialog({
893             xact_id : circ.id(),
894             patron : circ.usr()
895         });
896     }
897
898     $scope.retrieveAllPatrons = function() {
899         var users = new Set();
900         angular.forEach($scope.circ_list.map(function(circ) { return circ.usr(); }),function(usr) {
901             // aged circs have no 'usr'.
902             if (usr) users.add(usr);
903         });
904         users.forEach(function(usr) {
905             $timeout(function() {
906                 var url = $location.absUrl().replace(
907                     /\/cat\/.*/,
908                     '/circ/patron/' + usr.id() + '/checkout');
909                 $window.open(url, '_blank')
910             });
911         });
912     }
913
914     // load data for /circ_list tab
915     function loadCircHistory() {
916         $scope.circ_list = [];
917
918         var copy_org = 
919             itemSvc.copy.call_number().id() == -1 ?
920             itemSvc.copy.circ_lib().id() :
921             itemSvc.copy.call_number().owning_lib().id();
922
923         // there is an extra layer of permissibility over circ
924         // history views
925         egCore.perm.hasPermAt('VIEW_COPY_CHECKOUT_HISTORY', true)
926         .then(function(orgIds) {
927
928             if (orgIds.indexOf(copy_org) == -1) {
929                 console.log('User is not allowed to view circ history');
930                 return $q.when(0);
931             }
932
933             return fetchMaxCircHistory();
934
935         }).then(function(maxHistCount) {
936
937             if(!maxHistCount) $scope.isMaxCircHistoryZero = true;
938
939             egCore.pcrud.search('aacs',
940                 {target_copy : copyId},
941                 {   flesh : 2,
942                     flesh_fields : {
943                         aacs : [
944                             'usr',
945                             'workstation',
946                             'checkin_workstation',
947                             'recurring_fine_rule'
948                         ],
949                         au : ['card']
950                     },
951                     order_by : {aacs : 'xact_start desc'},
952                     // fetch at least one to see if copy ever circulated
953                     limit : $scope.isMaxCircHistoryZero ? 1 : maxHistCount
954                 }
955
956             ).then(null, null, function(circ) {
957
958                 $scope.circ = circ;
959
960                 // flesh circ_lib locally
961                 circ.circ_lib(egCore.org.get(circ.circ_lib()));
962                 circ.checkin_lib(egCore.org.get(circ.checkin_lib()));
963                 $scope.circ_list.push(circ);
964             });
965         });
966     }
967
968
969     function loadCircCounts() {
970
971         delete $scope.circ_counts;
972         $scope.total_circs = 0;
973         $scope.total_circs_this_year = 0;
974         $scope.total_circs_prev_year = 0;
975         if (!copyId) return;
976
977         egCore.pcrud.search('circbyyr', 
978             {copy : copyId}, null, {atomic : true})
979
980         .then(function(counts) {
981             $scope.circ_counts = counts;
982
983             angular.forEach(counts, function(count) {
984                 $scope.total_circs += Number(count.count());
985             });
986
987             var this_year = counts.filter(function(c) {
988                 return c.year() == new Date().getFullYear();
989             });
990
991             $scope.total_circs_this_year = (function() {
992                 total = 0;
993                 if (this_year.length == 2) {
994                     total = (Number(this_year[0].count()) + Number(this_year[1].count()));
995                 } else if (this_year.length == 1) {
996                     total = Number(this_year[0].count());
997                 }
998                 return total;
999             })();
1000
1001             var prev_year = counts.filter(function(c) {
1002                 return c.year() == new Date().getFullYear() - 1;
1003             });
1004
1005             $scope.total_circs_prev_year = (function() {
1006                 total = 0;
1007                 if (prev_year.length == 2) {
1008                     total = (Number(prev_year[0].count()) + Number(prev_year[1].count()));
1009                 } else if (prev_year.length == 1) {
1010                     total = Number(prev_year[0].count());
1011                 }
1012                 return total;
1013             })();
1014
1015         });
1016     }
1017
1018     function loadHolds() {
1019         delete $scope.hold;
1020         if (!copyId) return;
1021
1022         egCore.pcrud.search('ahr', 
1023             {   current_copy : copyId, 
1024                 cancel_time : null, 
1025                 fulfillment_time : null,
1026                 capture_time : {'<>' : null}
1027             }, {
1028                 flesh : 2,
1029                 flesh_fields : {
1030                     ahr : ['requestor', 'usr'],
1031                     au  : ['card']
1032                 }
1033             }
1034         ).then(null, null, function(hold) {
1035             $scope.hold = hold;
1036             hold.pickup_lib(egCore.org.get(hold.pickup_lib()));
1037             if (hold.current_shelf_lib()) {
1038                 hold.current_shelf_lib(
1039                     egCore.org.get(hold.current_shelf_lib()));
1040             }
1041             hold.behind_desk(Boolean(hold.behind_desk() == 't'));
1042         });
1043     }
1044
1045     function loadMostRecentTransit() {
1046         delete $scope.transit;
1047         delete $scope.hold_transit;
1048         if (!copyId) return;
1049
1050         egCore.pcrud.search('atc', 
1051             {target_copy : copyId},
1052             {
1053                 order_by : {atc : 'source_send_time DESC'},
1054                 limit : 1
1055             }
1056
1057         ).then(null, null, function(transit) {
1058             // use progress callback since we'll get up to one result
1059             $scope.transit = transit;
1060             transit.source(egCore.org.get(transit.source()));
1061             transit.dest(egCore.org.get(transit.dest()));
1062         })
1063     }
1064
1065
1066     // we don't need all data on all tabs, so fetch what's needed when needed.
1067     function loadTabData() {
1068         switch($scope.tab) {
1069             case 'summary':
1070                 loadCurrentCirc();
1071                 loadCircCounts();
1072                 break;
1073
1074             case 'circs':
1075                 loadCurrentCirc();
1076                 break;
1077
1078             case 'circ_list':
1079                 loadCircHistory();
1080                 break;
1081
1082             case 'holds':
1083                 loadHolds()
1084                 loadMostRecentTransit();
1085                 break;
1086
1087             case 'triggered_events':
1088                 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1089                 url += '?copy_id=' + encodeURIComponent(copyId);
1090                 $scope.triggered_events_url = url;
1091                 $scope.funcs = {};
1092         }
1093
1094         if ($scope.edit) {
1095             egCore.net.request(
1096                 'open-ils.actor',
1097                 'open-ils.actor.anon_cache.set_value',
1098                 null, 'edit-these-copies', {
1099                     record_id: $scope.recordId,
1100                     copies: [copyId],
1101                     hide_vols : true,
1102                     hide_copies : false
1103                 }
1104             ).then(function(key) {
1105                 if (key) {
1106                     var url = egCore.env.basePath + 'cat/volcopy/' + key;
1107                     $window.location.href = url;
1108                 } else {
1109                     alert('Could not create anonymous cache key!');
1110                 }
1111             });
1112         }
1113
1114         return;
1115     }
1116
1117     $scope.addCopyAlerts = function(copy_id) {
1118         egCirc.add_copy_alerts([copy_id]).then(function() {
1119             // force a refresh
1120             loadCopy($scope.copy.barcode()).then(loadTabData);
1121         });
1122     }
1123     $scope.manageCopyAlerts = function(copy_id) {
1124         egCirc.manage_copy_alerts([copy_id]).then(function() {
1125             // force a refresh
1126             loadCopy($scope.copy.barcode()).then(loadTabData);
1127         });
1128     }
1129
1130     $scope.context.toggleDisplay = function() {
1131         $location.path('/cat/item/search');
1132     }
1133
1134     // handle the barcode scan box, which will replace our current copy
1135     $scope.context.search = function(args) {
1136         loadCopy(args.barcode).then(loadTabData);
1137     }
1138
1139     $scope.context.show_triggered_events = function() {
1140         $location.path('/cat/item/' + copyId + '/triggered_events');
1141     }
1142
1143     loadCopy().then(loadTabData);
1144 }])