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