051797008a16435f4f6dbd4ce3a17a91ee15c2e5
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / catalog / app.js
1 /**
2  * TPAC Frame App
3  *
4  * currently, this app doesn't use routes for each sub-ui, because 
5  * reloading the catalog each time is sloooow.  better so far to 
6  * swap out divs w/ ng-if / ng-show / ng-hide as needed.
7  *
8  */
9
10 angular.module('egCatalogApp', ['ui.bootstrap','ngRoute','ngLocationUpdate','egCoreMod','egGridMod', 'egMarcMod', 'egUserMod', 'egHoldingsMod', 'ngToast'])
11
12 .config(['ngToastProvider', function(ngToastProvider) {
13   ngToastProvider.configure({
14     verticalPosition: 'bottom',
15     animation: 'fade'
16   });
17 }])
18
19 .config(function($routeProvider, $locationProvider, $compileProvider) {
20     $locationProvider.html5Mode(true);
21     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
22
23     var resolver = {delay : ['egCore','egStartup','egUser', function(egCore, egStartup, egUser) {
24         egCore.env.classLoaders.aous = function() {
25             return egCore.org.settings([
26                 'cat.marc_control_number_identifier'
27             ]).then(function(settings) {
28                 // local settings are cached within egOrg.  Caching them
29                 // again in egEnv just simplifies the syntax for access.
30                 egCore.env.aous = settings;
31             });
32         }
33         egCore.env.loadClasses.push('aous');
34         return egStartup.go()
35     }]};
36
37     $routeProvider.when('/cat/catalog/index', {
38         templateUrl: './cat/catalog/t_catalog',
39         controller: 'CatalogCtrl',
40         resolve : resolver
41     });
42
43     // Jump directly to the results page.  Any URL parameter 
44     // supported by the embedded catalog is supported here.
45     $routeProvider.when('/cat/catalog/results', {
46         templateUrl: './cat/catalog/t_catalog',
47         controller: 'CatalogCtrl',
48         resolve : resolver
49     });
50
51     $routeProvider.when('/cat/catalog/retrieve_by_id', {
52         templateUrl: './cat/catalog/t_retrieve_by_id',
53         controller: 'CatalogRecordRetrieve',
54         resolve : resolver
55     });
56
57     $routeProvider.when('/cat/catalog/retrieve_by_tcn', {
58         templateUrl: './cat/catalog/t_retrieve_by_tcn',
59         controller: 'CatalogRecordRetrieve',
60         resolve : resolver
61     });
62
63     $routeProvider.when('/cat/catalog/new_bib', {
64         templateUrl: './cat/catalog/t_new_bib',
65         controller: 'NewBibCtrl',
66         resolve : resolver
67     });
68
69     // create some catalog page-specific mappings
70     $routeProvider.when('/cat/catalog/record/:record_id', {
71         templateUrl: './cat/catalog/t_catalog',
72         controller: 'CatalogCtrl',
73         resolve : resolver
74     });
75
76     // create some catalog page-specific mappings
77     $routeProvider.when('/cat/catalog/record/:record_id/:record_tab', {
78         templateUrl: './cat/catalog/t_catalog',
79         controller: 'CatalogCtrl',
80         resolve : resolver
81     });
82
83     $routeProvider.when('/cat/catalog/batchEdit', {
84         templateUrl: './cat/catalog/t_batchedit',
85         controller: 'BatchEditCtrl',
86         resolve : resolver
87     });
88
89     $routeProvider.when('/cat/catalog/batchEdit/:container_type/:container_id', {
90         templateUrl: './cat/catalog/t_batchedit',
91         controller: 'BatchEditCtrl',
92         resolve : resolver
93     });
94
95     $routeProvider.when('/cat/catalog/vandelay', {
96         templateUrl: './cat/catalog/t_vandelay',
97         controller: 'VandelayCtrl',
98         resolve : resolver
99     });
100
101     $routeProvider.when('/cat/catalog/verifyURLs', {
102         templateUrl: './cat/catalog/t_verifyurls',
103         controller: 'URLVerifyCtrl',
104         resolve : resolver
105     });
106
107     $routeProvider.when('/cat/catalog/manageAuthorities', {
108         templateUrl: './cat/catalog/t_manageauthorities',
109         controller: 'ManageAuthoritiesCtrl',
110         resolve : resolver
111     });
112
113     $routeProvider.when('/cat/catalog/authority/:authority_id/marc_edit', {
114         templateUrl: './cat/catalog/t_authority',
115         controller: 'AuthorityCtrl',
116         resolve : resolver
117     });
118
119     $routeProvider.otherwise({redirectTo : '/cat/catalog/index'});
120 })
121
122
123 /**
124  * */
125 .controller('CatalogRecordRetrieve',
126        ['$scope','$routeParams','$location','$q','egCore',
127 function($scope , $routeParams , $location , $q , egCore ) {
128
129     $scope.focusMe = true;
130
131     // jump to the patron checkout UI
132     function loadRecord(record_id) {
133         $location
134         .path('/cat/catalog/record/' + record_id);
135     }
136
137     $scope.submitId = function(args) {
138         $scope.recordNotFound = null;
139         if (!args.record_id) return;
140
141         // blur so next time it's set to true it will re-apply select()
142         $scope.selectMe = false;
143
144         return loadRecord(args.record_id);
145     }
146
147     $scope.submitTCN = function(args) {
148         $scope.recordNotFound = null;
149         $scope.moreRecordsFound = null;
150         if (!args.record_tcn) return;
151
152         // blur so next time it's set to true it will re-apply select()
153         $scope.selectMe = false;
154
155         // lookup TCN
156         egCore.net.request(
157             'open-ils.search',
158             'open-ils.search.biblio.tcn',
159             args.record_tcn)
160
161         .then(function(resp) { // get_barcodes
162
163             if (evt = egCore.evt.parse(resp)) {
164                 alert(evt); // FIXME
165                 return;
166             }
167
168             if (!resp.count) {
169                 $scope.recordNotFound = args.record_tcn;
170                 $scope.selectMe = true;
171                 return;
172             }
173
174             if (resp.count > 1) {
175                 $scope.moreRecordsFound = args.record_tcn;
176                 $scope.selectMe = true;
177                 return;
178             }
179
180             var record_id = resp.ids[0];
181             return loadRecord(record_id);
182         });
183     }
184
185 }])
186
187 .controller('NewBibCtrl',
188        ['$scope','$routeParams','$location','$window','$q','egCore',
189         'egGridDataProvider','egHoldGridActions','$timeout','holdingsSvc',
190 function($scope , $routeParams , $location , $window , $q , egCore) {
191
192     $scope.have_template = false;
193     $scope.marc_template = '';
194     $scope.stop_unload = false;
195     $scope.template_list = [];
196     $scope.template_name = '';
197     $scope.new_bib_id = 0;
198
199     egCore.net.request(
200         'open-ils.cat',
201         'open-ils.cat.marc_template.types.retrieve'
202     ).then(function(resp) {
203         angular.forEach(resp, function(name) {
204             $scope.template_list.push(name);
205         });
206         $scope.template_list.sort();
207     });
208     $scope.template_name = egCore.hatch.getSessionItem('eg.cat.last_bib_marc_template');
209     if (!$scope.template_name) {
210         egCore.hatch.getItem('cat.default_bib_marc_template').then(function(template) {
211             $scope.template_name = template;
212         });
213     }
214
215     $scope.loadTemplate = function() {
216         if ($scope.template_name) {
217             egCore.net.request(
218                 'open-ils.cat',
219                 'open-ils.cat.biblio.marc_template.retrieve',
220                 $scope.template_name
221             ).then(function(template) {
222                 $scope.marc_template = template;
223                 $scope.have_template = true;
224                 egCore.hatch.setSessionItem('eg.cat.last_bib_marc_template', $scope.template_name);
225             });
226         }
227     }
228
229     $scope.setDefaultTemplate = function() {
230         var hatch_key = "cat.default_bib_marc_template";
231         if ($scope.template_name) {
232             egCore.hatch.setItem(hatch_key, $scope.template_name);
233         } else {
234             egCore.hatch.removeItem(hatch_key);
235         }
236     }
237
238     $scope.$watch('new_bib_id', function(newVal, oldVal) {
239         if (newVal) {
240             $location.path('/cat/catalog/record/' + $scope.new_bib_id);
241         }
242     });
243     
244
245 }])
246 .controller('CatalogCtrl',
247        ['$scope','$routeParams','$location','$window','$q','egCore','egHolds','egCirc','egConfirmDialog','ngToast',
248         'egGridDataProvider','egHoldGridActions','egProgressDialog','$timeout','$uibModal','holdingsSvc','egUser','conjoinedSvc',
249         '$cookies',
250 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc , egConfirmDialog , ngToast ,
251          egGridDataProvider , egHoldGridActions , egProgressDialog , $timeout , $uibModal , holdingsSvc , egUser , conjoinedSvc,
252          $cookies
253 ) {
254
255     var holdingsSvcInst = new holdingsSvc();
256
257     // set record ID on page load if available...
258     $scope.record_id = $routeParams.record_id;
259     $scope.summary_pane_record;
260
261     if ($routeParams.record_id) $scope.from_route = true;
262     else $scope.from_route = false;
263
264     // set search and preferred library cookies
265     egCore.hatch.getItem('eg.search.search_lib').then(function(val) {
266         $cookies.put('eg_search_lib', val, { path : '/' });
267     });
268     egCore.hatch.getItem('eg.search.pref_lib').then(function(val) {
269         $cookies.put('eg_pref_lib', val, { path : '/' });
270     });
271
272     // will hold a ref to the opac iframe
273     $scope.opac_iframe = null;
274     $scope.parts_iframe = null;
275
276     $scope.search_result_index = 1;
277     $scope.search_result_hit_count = 1;
278
279     $scope.$watch(
280         'opac_iframe.dom.contentWindow.search_result_index',
281         function (n,o) {
282             if (!isNaN(parseInt(n)))
283                 $scope.search_result_index = n + 1;
284         }
285     );
286
287     $scope.$watch(
288         'opac_iframe.dom.contentWindow.search_result_hit_count',
289         function (n,o) {
290             if (!isNaN(parseInt(n)))
291                 $scope.search_result_hit_count = n;
292         }
293     );
294
295     $scope.in_opac_call = false;
296     $scope.opac_call = function (opac_frame_function, force_opac_tab) {
297         if ($scope.opac_iframe) {
298             if (force_opac_tab) $scope.record_tab = 'catalog';
299             $scope.in_opac_call = true;
300             $scope.opac_iframe.dom.contentWindow[opac_frame_function]();
301             if (opac_frame_function == 'rdetailBackToResults') {
302                 $location.update_path('/cat/catalog/index');
303             }
304         }
305     }
306
307     $scope.add_to_record_bucket = function() {
308         var recId = $scope.record_id;
309         return $uibModal.open({
310             templateUrl: './cat/catalog/t_add_to_bucket',
311             animation: true,
312             size: 'md',
313             controller:
314                    ['$scope','$uibModalInstance',
315             function($scope , $uibModalInstance) {
316
317                 $scope.bucket_id = 0;
318                 $scope.newBucketName = '';
319                 $scope.allBuckets = [];
320                 egCore.net.request(
321                     'open-ils.actor',
322                     'open-ils.actor.container.retrieve_by_class.authoritative',
323                     egCore.auth.token(), egCore.auth.user().id(),
324                     'biblio', 'staff_client'
325                 ).then(function(buckets) { $scope.allBuckets = buckets; });
326
327                 $scope.add_to_bucket = function() {
328                     var item = new egCore.idl.cbrebi();
329                     item.bucket($scope.bucket_id);
330                     item.target_biblio_record_entry(recId);
331                     egCore.net.request(
332                         'open-ils.actor',
333                         'open-ils.actor.container.item.create',
334                         egCore.auth.token(), 'biblio', item
335                     ).then(function(resp) {
336                         $uibModalInstance.close();
337                     });
338                 }
339
340                 $scope.add_to_new_bucket = function() {
341                     var bucket = new egCore.idl.cbreb();
342                     bucket.owner(egCore.auth.user().id());
343                     bucket.name($scope.newBucketName);
344                     bucket.description('');
345                     bucket.btype('staff_client');
346
347                     egCore.net.request(
348                         'open-ils.actor',
349                         'open-ils.actor.container.create',
350                         egCore.auth.token(), 'biblio', bucket
351                     ).then(function(bucket) {
352                         $scope.bucket_id = bucket;
353                         $scope.add_to_bucket();
354                     });
355                 }
356
357                 $scope.cancel = function() {
358                     $uibModalInstance.dismiss();
359                 }
360             }]
361         });
362     }
363
364     $scope.current_overlay_target     = egCore.hatch.getLocalItem('eg.cat.marked_overlay_record');
365     $scope.current_voltransfer_target = egCore.hatch.getLocalItem('eg.cat.marked_volume_transfer_record');
366     $scope.current_conjoined_target   = egCore.hatch.getLocalItem('eg.cat.marked_conjoined_record');
367
368     $scope.markConjoined = function () {
369         $scope.current_conjoined_target = $scope.record_id;
370         egCore.hatch.setLocalItem('eg.cat.marked_conjoined_record',$scope.record_id);
371         ngToast.create(egCore.strings.MARK_CONJ_TARGET);
372     };
373
374     $scope.markVolTransfer = function () {
375         ngToast.create(egCore.strings.MARK_VOL_TARGET);
376         $scope.current_voltransfer_target = $scope.record_id;
377         egCore.hatch.setLocalItem('eg.cat.marked_volume_transfer_record',$scope.record_id);
378     };
379
380     $scope.markOverlay = function () {
381         $scope.current_overlay_target = $scope.record_id;
382         egCore.hatch.setLocalItem('eg.cat.marked_overlay_record',$scope.record_id);
383         ngToast.create(egCore.strings.MARK_OVERLAY_TARGET);
384     };
385
386     $scope.clearRecordMarks = function () {
387         $scope.current_overlay_target     = null;
388         $scope.current_voltransfer_target = null;
389         $scope.current_conjoined_target   = null;
390         $scope.current_hold_transfer_dest = null;
391         egCore.hatch.removeLocalItem('eg.cat.marked_volume_transfer_record');
392         egCore.hatch.removeLocalItem('eg.cat.marked_conjoined_record');
393         egCore.hatch.removeLocalItem('eg.cat.marked_overlay_record');
394         egCore.hatch.removeLocalItem('eg.circ.hold.title_transfer_target');
395     }
396
397     $scope.stop_unload = false;
398     $scope.$watch('stop_unload',
399         function(newVal, oldVal) {
400             if (newVal && newVal != oldVal && $scope.opac_iframe) {
401                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
402                     return 'There is unsaved data in this record.'
403                 });
404             } else {
405                 if ($scope.opac_iframe)
406                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
407             }
408         }
409     );
410
411     // Set the "last bib" cookie, if we have that
412     if ($scope.record_id)
413         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
414
415     $scope.refresh_record_callback = function (record_id) {
416         egCore.pcrud.retrieve('bre', record_id, {
417             flesh : 1,
418             flesh_fields : {
419                 bre : ['simple_record','creator','editor']
420             }
421         }).then(function(rec) {
422             rec.owner(egCore.org.get(rec.owner()));
423             $scope.summary_pane_record = rec;
424         });
425
426         return record_id;
427     }
428
429     // also set it when the iframe changes to a new record
430     $scope.handle_page = function(url) {
431
432         if (!url || url == 'about:blank') {
433             // nothing loaded.  If we already have a record ID, leave it.
434             return;
435         }
436
437         var match = url.match(/\/+opac\/+record\/+(\d+)/);
438         if (match) {
439             $scope.record_id = match[1];
440             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
441             $scope.holdings_record_id_changed($scope.record_id);
442             conjoinedSvc.fetch($scope.record_id).then(function(){
443                 $scope.conjoinedGridDataProvider.refresh();
444             });
445             init_parts_url();
446             $location.update_path('/cat/catalog/record/' + $scope.record_id);
447         } else {
448             delete $scope.record_id;
449             $scope.from_route = false;
450         }
451
452         // child scope is executing this function, so our digest doesn't fire ... thus,
453         $scope.$apply();
454
455         if (!$scope.in_opac_call) {
456             if ($scope.record_id) {
457                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
458                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
459             } else {
460                 tab = $routeParams.record_tab || 'catalog';
461             }
462             $scope.set_record_tab(tab);
463         } else {
464             $scope.in_opac_call = false;
465         }
466     }
467
468     // xulG catalog handlers
469     $scope.handlers = { }
470
471     // ------------------------------------------------------------------
472     // Conjoined items
473
474     $scope.conjoinedGridControls = {};
475     $scope.conjoinedGridDataProvider = egGridDataProvider.instance({
476         get : function(offset, count) {
477             return this.arrayNotifier(conjoinedSvc.items, offset, count);
478         }
479     });
480
481     $scope.changeConjoinedType = function () {
482         var peers = egCore.idl.Clone($scope.conjoinedGridControls.selectedItems());
483         angular.forEach(peers, function (p) {
484             p.target_copy(p.target_copy().id());
485             p.peer_type(p.peer_type().id());
486         });
487
488         var conjoinedGridDataProviderRef = $scope.conjoinedGridDataProvider;
489
490         return $uibModal.open({
491             templateUrl: './cat/catalog/t_conjoined_selector',
492             animation: true,
493             controller:
494                    ['$scope','$uibModalInstance',
495             function($scope , $uibModalInstance) {
496                 $scope.update = true;
497
498                 $scope.peer_type = null;
499                 $scope.peer_type_list = [];
500                 conjoinedSvc.get_peer_types().then(function(list){
501                     $scope.peer_type_list = list;
502                 });
503     
504                 $scope.ok = function(type) {
505                     var promises = [];
506     
507                     angular.forEach(peers, function (p) {
508                         p.ischanged(1);
509                         p.peer_type(type);
510                         promises.push(egCore.pcrud.update(p));
511                     });
512     
513                     return $q.all(promises)
514                         .then(function(){$uibModalInstance.close()})
515                         .then(function(){return conjoinedSvc.fetch()})
516                         .then(function(){conjoinedGridDataProviderRef.refresh()});
517                 }
518     
519                 $scope.cancel = function($event) {
520                     $uibModalInstance.dismiss();
521                     $event.preventDefault();
522                 }
523             }]
524         });
525         
526     }
527
528     $scope.refreshConjoined = function () {
529         conjoinedSvc.fetch($scope.record_id)
530         .then(function(){$scope.conjoinedGridDataProvider.refresh();});
531     }
532
533     $scope.deleteSelectedConjoined = function () {
534         var peers = $scope.conjoinedGridControls.selectedItems();
535
536         if (peers.length > 0) {
537             egConfirmDialog.open(
538                 egCore.strings.CONFIRM_DELETE_PEERS,
539                 egCore.strings.CONFIRM_DELETE_PEERS_MESSAGE,
540                 {peers : peers.length}
541             ).result.then(function() {
542                 angular.forEach(peers, function (p) {
543                     p.isdeleted(1);
544                 });
545
546                 egCore.pcrud.remove(peers).then(function() {
547                     return conjoinedSvc.fetch();
548                 }).then(function() {
549                     $scope.conjoinedGridDataProvider.refresh();
550                 });
551             });
552         }
553     }
554     if ($scope.record_id)
555         conjoinedSvc.fetch($scope.record_id);
556
557     // ------------------------------------------------------------------
558     // Holdings
559
560     $scope.holdingsGridControls = {
561         activateItem : function (item) {
562             $scope.selectedHoldingsVolCopyEdit();
563         }
564     };
565     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
566         get : function(offset, count) {
567             return this.arrayNotifier(holdingsSvcInst.copies, offset, count);
568         }
569     });
570
571     $scope.add_copies_to_bucket = function() {
572         var copy_list = gatherSelectedHoldingsIds();
573         if (copy_list.length == 0) return;
574
575         return $uibModal.open({
576             templateUrl: './cat/catalog/t_add_to_bucket',
577             animation: true,
578             size: 'md',
579             controller:
580                    ['$scope','$uibModalInstance',
581             function($scope , $uibModalInstance) {
582
583                 $scope.bucket_id = 0;
584                 $scope.newBucketName = '';
585                 $scope.allBuckets = [];
586
587                 egCore.net.request(
588                     'open-ils.actor',
589                     'open-ils.actor.container.retrieve_by_class.authoritative',
590                     egCore.auth.token(), egCore.auth.user().id(),
591                     'copy', 'staff_client'
592                 ).then(function(buckets) { $scope.allBuckets = buckets; });
593
594                 $scope.add_to_bucket = function() {
595                     var promises = [];
596                     angular.forEach(copy_list, function (cp) {
597                         var item = new egCore.idl.ccbi()
598                         item.bucket($scope.bucket_id);
599                         item.target_copy(cp);
600                         promises.push(
601                             egCore.net.request(
602                                 'open-ils.actor',
603                                 'open-ils.actor.container.item.create',
604                                 egCore.auth.token(), 'copy', item
605                             )
606                         );
607
608                         return $q.all(promises).then(function() {
609                             $uibModalInstance.close();
610                         });
611                     });
612                 }
613
614                 $scope.add_to_new_bucket = function() {
615                     var bucket = new egCore.idl.ccb();
616                     bucket.owner(egCore.auth.user().id());
617                     bucket.name($scope.newBucketName);
618                     bucket.description('');
619                     bucket.btype('staff_client');
620
621                     return egCore.net.request(
622                         'open-ils.actor',
623                         'open-ils.actor.container.create',
624                         egCore.auth.token(), 'copy', bucket
625                     ).then(function(bucket) {
626                         $scope.bucket_id = bucket;
627                         $scope.add_to_bucket();
628                     });
629                 }
630
631                 $scope.cancel = function() {
632                     $uibModalInstance.dismiss();
633                 }
634             }]
635         });
636     }
637
638     $scope.requestItems = function() {
639         var copy_list = gatherSelectedHoldingsIds();
640         if (copy_list.length == 0) return;
641
642         return $uibModal.open({
643             templateUrl: './cat/catalog/t_request_items',
644             animation: true,
645             controller:
646                    ['$scope','$uibModalInstance',
647             function($scope , $uibModalInstance) {
648                 $scope.user = null;
649                 $scope.first_user_fetch = true;
650
651                 $scope.hold_data = {
652                     hold_type : 'C',
653                     copy_list : copy_list,
654                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
655                     user      : egCore.auth.user().id()
656                 };
657
658                 egUser.get( $scope.hold_data.user ).then(function(u) {
659                     $scope.user = u;
660                     $scope.barcode = u.card().barcode();
661                     $scope.user_name = egUser.format_name(u);
662                     $scope.hold_data.user = u.id();
663                 });
664
665                 $scope.user_name = '';
666                 $scope.barcode = '';
667                 $scope.$watch('barcode', function (n) {
668                     if (!$scope.first_user_fetch) {
669                         egUser.getByBarcode(n).then(function(u) {
670                             $scope.user = u;
671                             $scope.user_name = egUser.format_name(u);
672                             $scope.hold_data.user = u.id();
673                         }, function() {
674                             $scope.user = null;
675                             $scope.user_name = '';
676                             delete $scope.hold_data.user;
677                         });
678                     }
679                     $scope.first_user_fetch = false;
680                 });
681
682                 $scope.ok = function(h) {
683                     var args = {
684                         patronid  : h.user,
685                         hold_type : h.hold_type,
686                         pickup_lib: h.pickup_lib.id(),
687                         depth     : 0
688                     };
689
690                     egCore.net.request(
691                         'open-ils.circ',
692                         'open-ils.circ.holds.test_and_create.batch.override',
693                         egCore.auth.token(), args, h.copy_list
694                     );
695
696                     $uibModalInstance.close();
697                 }
698
699                 $scope.cancel = function($event) {
700                     $uibModalInstance.dismiss();
701                     $event.preventDefault();
702                 }
703             }]
704         });
705     }
706
707     $scope.view_place_orders = function() {
708         if (!$scope.record_id) return;
709         var url = egCore.env.basePath + 'acq/legacy/lineitem/related/' + $scope.record_id + '?target=bib';
710         $timeout(function() { $window.open(url, '_blank') });
711     }
712
713     $scope.replaceBarcodes = function() {
714         var copy_list = gatherSelectedRawCopies();
715         if (copy_list.length == 0) return;
716
717         var holdingsGridDataProviderRef = $scope.holdingsGridDataProvider;
718
719         angular.forEach(copy_list, function (cp) {
720             $uibModal.open({
721                 templateUrl: './cat/share/t_replace_barcode',
722                 animation: true,
723                 controller:
724                            ['$scope','$uibModalInstance',
725                     function($scope , $uibModalInstance) {
726                         $scope.isModal = true;
727                         $scope.focusBarcode = false;
728                         $scope.focusBarcode2 = true;
729                         $scope.barcode1 = cp.barcode();
730
731                         $scope.updateBarcode = function() {
732                             $scope.copyNotFound = false;
733                             $scope.updateOK = false;
734                 
735                             egCore.pcrud.search('acp',
736                                 {deleted : 'f', barcode : $scope.barcode1})
737                             .then(function(copy) {
738                 
739                                 if (!copy) {
740                                     $scope.focusBarcode = true;
741                                     $scope.copyNotFound = true;
742                                     return;
743                                 }
744                 
745                                 $scope.copyId = copy.id();
746                                 copy.barcode($scope.barcode2);
747                 
748                                 egCore.pcrud.update(copy).then(function(stat) {
749                                     $scope.updateOK = stat;
750                                     $scope.focusBarcode = true;
751                                     holdingsSvc.fetchAgain().then(function (){
752                                         holdingsGridDataProviderRef.refresh();
753                                     });
754                                 });
755
756                             });
757                             $uibModalInstance.close();
758                         }
759
760                         $scope.cancel = function($event) {
761                             $uibModalInstance.dismiss();
762                             $event.preventDefault();
763                         }
764                     }
765                 ]
766             });
767         });
768     }
769
770     // refresh the list of holdings when the record_id is changed.
771     $scope.holdings_record_id_changed = function(id) {
772         if ($scope.record_id != id) $scope.record_id = id;
773         console.log('record id changed to ' + id + ', loading new holdings');
774         holdingsSvcInst.fetch({
775             rid : $scope.record_id,
776             org : $scope.holdings_ou,
777             copy: $scope.holdings_show_copies,
778             vol : $scope.holdings_show_vols,
779             empty: $scope.holdings_show_empty
780         }).then(function() {
781             $scope.holdingsGridDataProvider.refresh();
782         });
783     }
784
785     // refresh the list of holdings when the filter lib is changed.
786     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
787     $scope.holdings_ou_changed = function(org) {
788         $scope.holdings_ou = org;
789         holdingsSvcInst.fetch({
790             rid : $scope.record_id,
791             org : $scope.holdings_ou,
792             copy: $scope.holdings_show_copies,
793             vol : $scope.holdings_show_vols,
794             empty: $scope.holdings_show_empty
795         }).then(function() {
796             $scope.holdingsGridDataProvider.refresh();
797         });
798     }
799
800     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
801         $scope[cb] = newVal;
802         egCore.hatch.setItem('cat.' + cb, newVal);
803         if (!norefresh) holdingsSvcInst.fetch({
804             rid : $scope.record_id,
805             org : $scope.holdings_ou,
806             copy: $scope.holdings_show_copies,
807             vol : $scope.holdings_show_vols,
808             empty: $scope.holdings_show_empty
809         }).then(function() {
810             $scope.holdingsGridDataProvider.refresh();
811         });
812     }
813
814     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
815         if (typeof x ==  'undefined') x = true;
816         $scope.holdings_cb_changed('holdings_show_vols',x,true);
817         $('#holdings_show_vols').prop('checked', x);
818     }).then(function(){
819         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
820             if (typeof x ==  'undefined') x = true;
821             $scope.holdings_cb_changed('holdings_show_copies',x,true);
822             $('#holdings_show_copies').prop('checked', x);
823         }).then(function(){
824             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
825                 if (typeof x ==  'undefined') x = true;
826                 $scope.holdings_cb_changed('holdings_show_empty',x);
827                 $('#holdings_show_empty').prop('checked', x);
828             })
829         })
830     });
831
832     $scope.vols_not_shown = function () {
833         return !$scope.holdings_show_vols;
834     }
835
836     $scope.copies_not_shown = function () {
837         return !$scope.holdings_show_copies;
838     }
839
840     $scope.holdings_checkbox_handler = function (item) {
841         $scope.holdings_cb_changed(item.checkbox,item.checked);
842     }
843
844     function gatherSelectedHoldingsIds () {
845         var cp_id_list = [];
846         angular.forEach(
847             $scope.holdingsGridControls.selectedItems(),
848             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
849         );
850         return cp_id_list;
851     }
852
853     function gatherSelectedRawCopies () {
854         var cp_list = [];
855         angular.forEach(
856             $scope.holdingsGridControls.selectedItems(),
857             function (item) { if (item.raw) cp_list = cp_list.concat(item.raw) }
858         );
859         return cp_list;
860     }
861
862     function gatherSelectedEmptyVolumeIds () {
863         var cn_id_list = [];
864         angular.forEach(
865             $scope.holdingsGridControls.selectedItems(),
866             function (item) {
867                 if (item.copy_count == 0)
868                     cn_id_list.push(item.call_number.id)
869             }
870         );
871         return cn_id_list;
872     }
873
874     function gatherSelectedVolumeIds () {
875         var cn_id_list = [];
876         angular.forEach(
877             $scope.holdingsGridControls.selectedItems(),
878             function (item) {
879                 if (cn_id_list.indexOf(item.call_number.id) == -1)
880                     cn_id_list.push(item.call_number.id)
881             }
882         );
883         return cn_id_list;
884     }
885
886     $scope.selectedHoldingsDelete = function (vols, copies) {
887
888         var cnHash = {};
889         var perCnCopies = {};
890
891         var cn_count = 0;
892         var cp_count = 0;
893
894         angular.forEach(
895             $scope.holdingsGridControls.selectedItems(),
896             function (item) {
897                 if (vols && item.raw_call_number) {
898                     cnHash[item.call_number.id] = egCore.idl.Clone(item.raw_call_number);
899                     cnHash[item.call_number.id].isdeleted(1);
900                     cn_count++;
901                 } else if (copies) {
902                     angular.forEach(egCore.idl.Clone(item.raw), function (cp) {
903                         cp.isdeleted(1);
904                         cp_count++;
905                         var cn_id = cp.call_number().id();
906                         if (!cnHash[cn_id]) {
907                             cnHash[cn_id] = cp.call_number();
908                             perCnCopies[cn_id] = [cp];
909                         } else {
910                             perCnCopies[cn_id].push(cp);
911                         }
912                         cp.call_number(cn_id); // prevent loops in JSON-ification
913                     });
914
915                 }
916             }
917         );
918
919         angular.forEach(perCnCopies, function (v, k) {
920             if (vols) {
921                 cnHash[k].isdeleted(1);
922                 cn_count++;
923             }
924             cnHash[k].copies(v);
925         });
926
927         cnList = [];
928         angular.forEach(cnHash, function (v, k) {
929             cnList.push(v);
930         });
931
932         if (cnList.length == 0) return;
933
934         var flags = {};
935         if (vols && copies) flags.force_delete_copies = 1;
936
937         egConfirmDialog.open(
938             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
939             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
940             {copies : cp_count, volumes : cn_count}
941         ).result.then(function() {
942             egCore.net.request(
943                 'open-ils.cat',
944                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
945                 egCore.auth.token(), cnList, 1, flags
946             ).then(function(update_count) {
947                 holdingsSvcInst.fetchAgain().then(function() {
948                     $scope.holdingsGridDataProvider.refresh();
949                 });
950             });
951         });
952     }
953     $scope.selectedHoldingsCopyDelete = function () { $scope.selectedHoldingsDelete(false,true) }
954     $scope.selectedHoldingsVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,true) }
955     $scope.selectedHoldingsEmptyVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,false) }
956
957     spawnHoldingsAdd = function (vols,copies){
958         var raw = [];
959         if (copies) { // just a copy on existing volumes
960             angular.forEach(gatherSelectedVolumeIds(), function (v) {
961                 raw.push( {callnumber : v} );
962             });
963         } else if (vols) {
964             if (typeof $scope.holdingsGridControls.selectedItems == "function" &&
965                 $scope.holdingsGridControls.selectedItems().length > 0) {
966                 angular.forEach($scope.holdingsGridControls.selectedItems(),
967                     function (item) {
968                         raw.push({
969                             owner : item.owner_id,
970                             label : item.call_number.label
971                         });
972                     });
973             } else {
974                 raw.push({
975                     owner : egCore.auth.user().ws_ou()
976                 });
977             }
978         }
979
980         if (raw.length == 0) raw.push({});
981
982         egCore.net.request(
983             'open-ils.actor',
984             'open-ils.actor.anon_cache.set_value',
985             null, 'edit-these-copies', {
986                 record_id: $scope.record_id,
987                 raw: raw,
988                 hide_vols : false,
989                 hide_copies : false
990             }
991         ).then(function(key) {
992             if (key) {
993                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
994                 $timeout(function() { $window.open(url, '_blank') });
995             } else {
996                 alert('Could not create anonymous cache key!');
997             }
998         });
999     }
1000     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(true,false) }
1001     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(false,true) }
1002
1003     spawnHoldingsEdit = function (hide_vols,hide_copies){
1004         egCore.net.request(
1005             'open-ils.actor',
1006             'open-ils.actor.anon_cache.set_value',
1007             null, 'edit-these-copies', {
1008                 record_id: $scope.record_id,
1009                 copies: gatherSelectedHoldingsIds(),
1010                 raw: gatherSelectedEmptyVolumeIds().map(
1011                     function(v){ return { callnumber : v } }
1012                 ),
1013                 hide_vols : hide_vols,
1014                 hide_copies : hide_copies
1015             }
1016         ).then(function(key) {
1017             if (key) {
1018                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
1019                 $timeout(function() { $window.open(url, '_blank') });
1020             } else {
1021                 alert('Could not create anonymous cache key!');
1022             }
1023         });
1024     }
1025     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
1026     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
1027     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
1028
1029     $scope.selectedHoldingsItemStatus = function (){
1030         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
1031         $timeout(function() { $window.open(url, '_blank') });
1032     }
1033
1034     $scope.markVolAsItemTarget = function() {
1035         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed
1036             egCore.hatch.setLocalItem(
1037                 'eg.cat.item_transfer_target',
1038                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
1039             );
1040             ngToast.create(egCore.strings.MARK_ITEM_TARGET);
1041         }
1042     }
1043
1044     $scope.markLibAsVolTarget = function() {
1045         return $uibModal.open({
1046             templateUrl: './cat/catalog/t_choose_vol_target_lib',
1047             animation: true,
1048             controller:
1049                    ['$scope','$uibModalInstance',
1050             function($scope , $uibModalInstance) {
1051
1052                 var orgId = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target') || 1;
1053                 $scope.org = egCore.org.get(orgId);
1054                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1055                 $scope.ok = function(org) {
1056                     egCore.hatch.setLocalItem(
1057                         'eg.cat.volume_transfer_target',
1058                         org.id()
1059                     );
1060                     $uibModalInstance.close();
1061                 }
1062                 $scope.cancel = function($event) {
1063                     $uibModalInstance.dismiss();
1064                     $event.preventDefault();
1065                 }
1066             }]
1067         });
1068     }
1069     $scope.markLibFromSelectedAsVolTarget = function() {
1070         egCore.hatch.setLocalItem(
1071             'eg.cat.volume_transfer_target',
1072             $scope.holdingsGridControls.selectedItems()[0].owner_id
1073         );
1074         ngToast.create(egCore.strings.MARK_VOL_TARGET);
1075     }
1076
1077     $scope.selectedHoldingsItemStatusDetail = function (){
1078         angular.forEach(
1079             gatherSelectedHoldingsIds(),
1080             function (cid) {
1081                 var url = egCore.env.basePath +
1082                           'cat/item/' + cid;
1083                 $timeout(function() { $window.open(url, '_blank') });
1084             }
1085         );
1086     }
1087
1088     $scope.transferVolumesToRecord = function (){
1089         var target_record = egCore.hatch.getLocalItem('eg.cat.marked_volume_transfer_record');
1090         if (!target_record) return;
1091         if ($scope.record_id == target_record) return;
1092         var items = $scope.holdingsGridControls.selectedItems();
1093         if (!items.length) return;
1094
1095         var vols_to_move   = {};
1096         angular.forEach(items, function(item) {
1097             if (!(item.call_number.owning_lib in vols_to_move)) {
1098                 vols_to_move[item.call_number.owning_lib] = new Array;
1099             }
1100             vols_to_move[item.call_number.owning_lib].push(item.call_number.id);
1101         });
1102
1103         var promises = [];        
1104         angular.forEach(vols_to_move, function(vols, owning_lib) {
1105             promises.push(egCore.net.request(
1106                 'open-ils.cat',
1107                 'open-ils.cat.asset.volume.batch.transfer.override',
1108                 egCore.auth.token(), {
1109                     docid   : target_record,
1110                     lib     : owning_lib,
1111                     volumes : vols
1112                 }
1113             ));
1114         });
1115         $q.all(promises).then(function(success) {
1116             if (success) {
1117                 ngToast.create(egCore.strings.VOLS_TRANSFERED);
1118                 holdingsSvcInst.fetchAgain().then(function() {
1119                     $scope.holdingsGridDataProvider.refresh();
1120                 });
1121             } else {
1122                 alert('Could not transfer volumes!');
1123             }
1124         });
1125     }
1126
1127     function transferVolumes(new_record){
1128         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
1129
1130         if (xfer_target) {
1131             egCore.net.request(
1132                 'open-ils.cat',
1133                 'open-ils.cat.asset.volume.batch.transfer.override',
1134                 egCore.auth.token(), {
1135                     docid   : (new_record ? new_record : $scope.record_id),
1136                     lib     : xfer_target,
1137                     volumes : gatherSelectedVolumeIds()
1138                 }
1139             ).then(function(success) {
1140                 if (success) {
1141                     ngToast.create(egCore.strings.VOLS_TRANSFERED);
1142                     holdingsSvcInst.fetchAgain().then(function() {
1143                         $scope.holdingsGridDataProvider.refresh();
1144                     });
1145                 } else {
1146                     alert('Could not transfer volumes!');
1147                 }
1148             });
1149         }
1150         
1151     }
1152
1153     $scope.transferVolumesToLibrary = function() {
1154         transferVolumes();
1155     }
1156
1157     $scope.transferVolumesToRecordAndLibrary = function() {
1158         var target_record = egCore.hatch.getLocalItem('eg.cat.marked_volume_transfer_record');
1159         if (!target_record) return;
1160         transferVolumes(target_record);
1161     }
1162
1163     // this "transfers" selected copies to a new owning library,
1164     // auto-creating volumes and deleting unused volumes as required.
1165     $scope.changeItemOwningLib = function() {
1166         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
1167         var items = $scope.holdingsGridControls.selectedItems();
1168         if (!xfer_target || !items.length) {
1169             return;
1170         }
1171         var vols_to_move   = {};
1172         var copies_to_move = {};
1173         angular.forEach(items, function(item) {
1174             if (item.call_number.owning_lib != xfer_target) {
1175                 if (item.call_number.id in vols_to_move) {
1176                     copies_to_move[item.call_number.id].push(item.id);
1177                 } else {
1178                     vols_to_move[item.call_number.id] = item.call_number;
1179                     copies_to_move[item.call_number.id] = new Array;
1180                     copies_to_move[item.call_number.id].push(item.id);
1181                 }
1182             }
1183         });
1184     
1185         var promises = [];
1186         angular.forEach(vols_to_move, function(vol) {
1187             promises.push(egCore.net.request(
1188                 'open-ils.cat',
1189                 'open-ils.cat.call_number.find_or_create',
1190                 egCore.auth.token(),
1191                 vol.label,
1192                 vol.record,
1193                 xfer_target,
1194                 vol.prefix.id,
1195                 vol.suffix.id,
1196                 vol.label_class
1197             ).then(function(resp) {
1198                 var evt = egCore.evt.parse(resp);
1199                 if (evt) return;
1200                 return egCore.net.request(
1201                     'open-ils.cat',
1202                     'open-ils.cat.transfer_copies_to_volume',
1203                     egCore.auth.token(),
1204                     resp.acn_id,
1205                     copies_to_move[vol.id]
1206                 );
1207             }));
1208         });
1209         $q.all(promises).then(function() {
1210             ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1211             holdingsSvcInst.fetchAgain().then(function() {
1212                 $scope.holdingsGridDataProvider.refresh();
1213             });
1214         });
1215     }
1216
1217     $scope.transferItems = function (){
1218         var xfer_target = egCore.hatch.getLocalItem('eg.cat.item_transfer_target');
1219         var copy_ids = gatherSelectedHoldingsIds();
1220         if (xfer_target && copy_ids.length > 0) {
1221             egCore.net.request(
1222                 'open-ils.cat',
1223                 'open-ils.cat.transfer_copies_to_volume',
1224                 egCore.auth.token(),
1225                 xfer_target,
1226                 copy_ids
1227             ).then(
1228                 function(resp) { // oncomplete
1229                     var evt = egCore.evt.parse(resp);
1230                     if (evt) {
1231                         egConfirmDialog.open(
1232                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_TITLE,
1233                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_BODY,
1234                             {'evt_desc': evt.desc}
1235                         ).result.then(function() {
1236                             egCore.net.request(
1237                                 'open-ils.cat',
1238                                 'open-ils.cat.transfer_copies_to_volume.override',
1239                                 egCore.auth.token(),
1240                                 xfer_target,
1241                                 copy_ids,
1242                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
1243                             ).then(function(resp) {
1244                                 holdingsSvcInst.fetchAgain().then(function() {
1245                                     $scope.holdingsGridDataProvider.refresh();
1246                                 });
1247                             });
1248                         });
1249                     } else {
1250                         ngToast.create(egCore.strings.ITEMS_TRANSFERED);
1251                         holdingsSvcInst.fetchAgain().then(function() {
1252                             $scope.holdingsGridDataProvider.refresh();
1253                         });
1254                     }
1255                 },
1256                 null, // onerror
1257                 null // onprogress
1258             )
1259         }
1260     }
1261
1262     $scope.selectedHoldingsItemStatusTgrEvt = function (){
1263         angular.forEach(
1264             gatherSelectedHoldingsIds(),
1265             function (cid) {
1266                 var url = egCore.env.basePath +
1267                           'cat/item/' + cid + '/triggered_events';
1268                 $timeout(function() { $window.open(url, '_blank') });
1269             }
1270         );
1271     }
1272
1273     $scope.selectedHoldingsItemStatusHolds = function (){
1274         angular.forEach(
1275             gatherSelectedHoldingsIds(),
1276             function (cid) {
1277                 var url = egCore.env.basePath +
1278                           'cat/item/' + cid + '/holds';
1279                 $timeout(function() { $window.open(url, '_blank') });
1280             }
1281         );
1282     }
1283
1284     $scope.selectedHoldingsDamaged = function () {
1285         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
1286             holdingsSvcInst.fetchAgain().then(function() {
1287                 $scope.holdingsGridDataProvider.refresh();
1288             });
1289         });
1290     }
1291
1292     $scope.selectedHoldingsMissing = function () {
1293         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
1294             holdingsSvcInst.fetchAgain().then(function() {
1295                 $scope.holdingsGridDataProvider.refresh();
1296             });
1297         });
1298     }
1299
1300     $scope.attach_to_peer_bib = function() {
1301         var copy_list = gatherSelectedHoldingsIds();
1302         if (copy_list.length == 0) return;
1303
1304         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
1305             if (!target_record) return;
1306
1307             return $uibModal.open({
1308                 templateUrl: './cat/catalog/t_conjoined_selector',
1309                 animation: true,
1310                 controller:
1311                        ['$scope','$uibModalInstance',
1312                 function($scope , $uibModalInstance) {
1313                     $scope.update = false;
1314
1315                     $scope.peer_type = null;
1316                     $scope.peer_type_list = [];
1317                     conjoinedSvc.get_peer_types().then(function(list){
1318                         $scope.peer_type_list = list;
1319                     });
1320     
1321                     $scope.ok = function(type) {
1322                         var promises = [];
1323     
1324                         angular.forEach(copy_list, function (cp) {
1325                             var n = new egCore.idl.bpbcm();
1326                             n.isnew(true);
1327                             n.peer_record(target_record);
1328                             n.target_copy(cp);
1329                             n.peer_type(type);
1330                             promises.push(egCore.pcrud.create(n));
1331                         });
1332     
1333                         return $q.all(promises).then(function(){$uibModalInstance.close()});
1334                     }
1335     
1336                     $scope.cancel = function($event) {
1337                         $uibModalInstance.dismiss();
1338                         $event.preventDefault();
1339                     }
1340                 }]
1341             });
1342         });
1343     }
1344
1345
1346     // ------------------------------------------------------------------
1347     // Holds 
1348     var provider = egGridDataProvider.instance({});
1349     $scope.hold_grid_data_provider = provider;
1350     $scope.grid_actions = egHoldGridActions;
1351     $scope.grid_actions.refresh = function () { provider.refresh() };
1352     $scope.hold_grid_controls = {};
1353
1354     var hold_ids = []; // current list of holds
1355     function fetchHolds(offset, count) {
1356         var ids = hold_ids.slice(offset, offset + count);
1357
1358         return egHolds.fetch_holds(ids).then(null, null,
1359             function(hold_data) { 
1360                 return hold_data;
1361             }
1362         );
1363     }
1364
1365     provider.get = function(offset, count) {
1366         if ($scope.record_tab != 'holds') return $q.when();
1367         var deferred = $q.defer();
1368         hold_ids = []; // no caching ATM
1369
1370         // open a determinate progress dialog, max value set below.
1371         egProgressDialog.open({max : 1, value : 0});
1372
1373         // fetch the IDs
1374         egCore.net.request(
1375             'open-ils.circ',
1376             'open-ils.circ.holds.retrieve_all_from_title',
1377             egCore.auth.token(), $scope.record_id, 
1378             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
1379         ).then(
1380             function(hold_data) {
1381                 angular.forEach(hold_data, function(list, type) {
1382                     hold_ids = hold_ids.concat(list);
1383                 });
1384
1385                 // Set the max value of the progress bar to the lesser of
1386                 // the total number of holds to fetch or the page size
1387                 // of the grid.
1388                 egProgressDialog.update(
1389                     {max : Math.min(hold_ids.length, count)});
1390
1391                 var holds_fetched = 0;
1392                 fetchHolds(offset, count)
1393                 .then(deferred.resolve, null, 
1394                     function(hold_data) {
1395                         holds_fetched++;
1396                         deferred.notify(hold_data);
1397                         egProgressDialog.increment();
1398                     }
1399                 )['finally'](egProgressDialog.close);
1400             }
1401         );
1402
1403         return deferred.promise;
1404     }
1405
1406     $scope.detail_view = function(action, user_data, items) {
1407         if (h = items[0]) {
1408             $scope.detail_hold_id = h.hold.id();
1409         }
1410     }
1411
1412     $scope.list_view = function(items) {
1413          $scope.detail_hold_id = null;
1414     }
1415
1416     // refresh the list of record holds when the pickup lib is changed.
1417     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
1418     $scope.pickup_ou_changed = function(org) {
1419         $scope.pickup_ou = org;
1420         provider.refresh();
1421     }
1422
1423     $scope.print_holds = function() {
1424         var holds = [];
1425         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
1426             holds.push({
1427                 hold : egCore.idl.toHash(item.hold),
1428                 patron_last : item.patron_last,
1429                 patron_alias : item.patron_alias,
1430                 patron_barcode : item.patron_barcode,
1431                 copy : egCore.idl.toHash(item.copy),
1432                 volume : egCore.idl.toHash(item.volume),
1433                 title : item.mvr.title(),
1434                 author : item.mvr.author()
1435             });
1436         });
1437
1438         egCore.print.print({
1439             context : 'receipt', 
1440             template : 'holds_for_bib', 
1441             scope : {holds : holds}
1442         });
1443     }
1444
1445     $scope.current_hold_transfer_dest = egCore.hatch.getLocalItem ('eg.circ.hold.title_transfer_target');
1446
1447     $scope.mark_hold_transfer_dest = function() {
1448         $scope.current_hold_transfer_dest = $scope.record_id;
1449         egCore.hatch.setLocalItem(
1450             'eg.circ.hold.title_transfer_target', $scope.record_id);
1451         ngToast.create(egCore.strings.HOLD_TRANSFER_DEST_MARKED);
1452     }
1453
1454     // UI presents this option as "all holds"
1455     $scope.transfer_holds_to_marked = function() {
1456         var hold_ids = $scope.hold_grid_controls.allItems().map(
1457             function(hold_data) {return hold_data.hold.id()});
1458         egHolds.transfer_to_marked_title(hold_ids);
1459     }
1460
1461     // ------------------------------------------------------------------
1462     // Initialize the selected tab
1463
1464     function init_cat_url() {
1465         // Set the initial catalog URL.  This only happens once.
1466         // The URL is otherwise generated through user navigation.
1467         if ($scope.catalog_url) return; 
1468
1469         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
1470
1471         // A record ID in the path indicates a request for the record-
1472         // specific page.
1473         if ($routeParams.record_id) {
1474             url = url.replace(/advanced/, '/record/' + $scope.record_id);
1475         }
1476
1477         // Jumping directly to the results page by passing a search
1478         // query via the URL.  Copy all URL params to the iframe url.
1479         if ($location.path().match(/catalog\/results/)) {
1480             url = url.replace(/advanced/, '/results?');
1481             var first = true;
1482             angular.forEach($location.search(), function(val, key) {
1483                 if (!first) url += '&';
1484                 first = false;
1485                 url += encodeURIComponent(key) 
1486                     + '=' + encodeURIComponent(val);
1487             });
1488         }
1489
1490         // if we're displaying the advanced search form, select
1491         // whatever default pane the user has chosen via workstation
1492         // preference
1493         if (url.match(/\/opac\/advanced$/)) {
1494             var adv_pane = egCore.hatch.getLocalItem('eg.search.adv_pane');
1495             if (adv_pane) {
1496                 url += '?pane=' + encodeURIComponent(adv_pane);
1497             }
1498         }
1499
1500         $scope.catalog_url = url;
1501     }
1502
1503     function init_parts_url() {
1504         $scope.parts_url = $location
1505             .absUrl()
1506             .replace(
1507                 /\/staff.*/,
1508                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
1509             );
1510     }
1511
1512     $scope.set_record_tab = function(tab) {
1513         $scope.record_tab = tab;
1514
1515         switch(tab) {
1516
1517             case 'monoparts':
1518                 init_parts_url();
1519                 break;
1520
1521             case 'catalog':
1522                 init_cat_url();
1523                 break;
1524
1525             case 'holds':
1526                 $scope.detail_hold_record_id = $scope.record_id; 
1527                 // refresh the holds grid
1528                 provider.refresh();
1529
1530                 break;
1531         }
1532     }
1533
1534     $scope.set_default_record_tab = function() {
1535         egCore.hatch.setLocalItem(
1536             'eg.cat.default_record_tab', $scope.record_tab);
1537         $timeout(function(){$scope.default_tab = $scope.record_tab});
1538     }
1539
1540     var tab;
1541     if ($scope.record_id) {
1542         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
1543         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
1544
1545     } else {
1546         tab = $routeParams.record_tab || 'catalog';
1547     }
1548     $scope.set_record_tab(tab);
1549
1550 }])
1551
1552 .controller('AuthorityCtrl',
1553        ['$scope','$routeParams','$location','$window','$q','egCore',
1554 function($scope , $routeParams , $location , $window , $q , egCore) {
1555
1556     // set record ID on page load if available...
1557     $scope.authority_id = $routeParams.authority_id;
1558
1559     if ($routeParams.authority_id) $scope.from_route = true;
1560     else $scope.from_route = false;
1561
1562     $scope.stop_unload = false;
1563 }])
1564
1565 .controller('URLVerifyCtrl',
1566        ['$scope','$location',
1567 function($scope , $location) {
1568     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
1569 }])
1570
1571 .controller('VandelayCtrl',
1572        ['$scope','$location',
1573 function($scope , $location) {
1574     $scope.vandelay_url = $location.absUrl().replace(/\/staff\/cat\/catalog\/vandelay/, '/vandelay/vandelay');
1575 }])
1576
1577 .controller('ManageAuthoritiesCtrl',
1578        ['$scope','$location',
1579 function($scope , $location) {
1580     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
1581 }])
1582
1583 .controller('BatchEditCtrl',
1584        ['$scope','$location','$routeParams',
1585 function($scope , $location , $routeParams) {
1586     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
1587     if ($routeParams.container_type) {
1588         switch ($routeParams.container_type) {
1589             case 'bucket':
1590                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
1591                 break;
1592             case 'record':
1593                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
1594                 break;
1595         };
1596     }
1597 }])
1598
1599  
1600 .filter('boolText', function(){
1601     return function (v) {
1602         return v == 't';
1603     }
1604 })
1605
1606 .factory('conjoinedSvc', 
1607        ['egCore','$q',
1608 function(egCore , $q) {
1609
1610     var service = {
1611         items : [], // record search results
1612         index : 0, // search grid index
1613         rid : null
1614     };
1615
1616     service.flesh = {   
1617         flesh : 4, 
1618         flesh_fields : {
1619             bpbcm : ['target_copy','peer_type'],
1620             acp : ['call_number'],
1621             acn : ['record'],
1622             bre : ['simple_record']
1623         },
1624         // avoid fetching the MARC blob by specifying which
1625         // fields on the bre to select.  More may be needed.
1626         // note that fleshed fields are explicitly selected.
1627         select : { bre : ['id'] },
1628         order_by : { bpbcm : ['id'] },
1629     }
1630
1631     // resolved with the last received copy
1632     service.fetch = function(rid) {
1633         if (!rid && !service.rid) return $q.when();
1634
1635         if (rid) service.rid = rid;
1636         service.items = [];
1637         service.index = 0;
1638
1639         return egCore.pcrud.search(
1640             'bpbcm',
1641             {peer_record : service.rid},
1642             service.flesh,
1643             {atomic : true}
1644         ).then( function(list) { // finished
1645             service.items = list;
1646             return service.items;
1647         });
1648     }
1649
1650     // returns a promise resolved with the list of peer bib types
1651     service.get_peer_types = function() {
1652         if (egCore.env.bpt)
1653             return $q.when(egCore.env.bpt.list);
1654
1655         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
1656         .then(function(list) {
1657             egCore.env.absorbList(list, 'bpt');
1658             return list;
1659         });
1660     };
1661
1662     return service;
1663 }])
1664
1665