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