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