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