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