]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/catalog/app.js
webstaff: Support adding copies and volumes
[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','egCoreMod','egGridMod', 'egMarcMod'])
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', function(egCore,  egStartup) {
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     // create some catalog page-specific mappings
49     $routeProvider.when('/cat/catalog/record/:record_id', {
50         templateUrl: './cat/catalog/t_catalog',
51         controller: 'CatalogCtrl',
52         resolve : resolver
53     });
54
55     // create some catalog page-specific mappings
56     $routeProvider.when('/cat/catalog/record/:record_id/:record_tab', {
57         templateUrl: './cat/catalog/t_catalog',
58         controller: 'CatalogCtrl',
59         resolve : resolver
60     });
61
62     $routeProvider.when('/cat/catalog/batchEdit', {
63         templateUrl: './cat/catalog/t_batchedit',
64         controller: 'BatchEditCtrl',
65         resolve : resolver
66     });
67
68     $routeProvider.when('/cat/catalog/batchEdit/:container_type/:container_id', {
69         templateUrl: './cat/catalog/t_batchedit',
70         controller: 'BatchEditCtrl',
71         resolve : resolver
72     });
73
74     $routeProvider.when('/cat/catalog/vandelay', {
75         templateUrl: './cat/catalog/t_vandelay',
76         controller: 'VandelayCtrl',
77         resolve : resolver
78     });
79
80     $routeProvider.when('/cat/catalog/verifyURLs', {
81         templateUrl: './cat/catalog/t_verifyurls',
82         controller: 'URLVerifyCtrl',
83         resolve : resolver
84     });
85
86     $routeProvider.when('/cat/catalog/manageAuthorities', {
87         templateUrl: './cat/catalog/t_manageauthorities',
88         controller: 'ManageAuthoritiesCtrl',
89         resolve : resolver
90     });
91
92     $routeProvider.when('/cat/catalog/authority/:authority_id/marc_edit', {
93         templateUrl: './cat/catalog/t_authority',
94         controller: 'AuthorityCtrl',
95         resolve : resolver
96     });
97
98     $routeProvider.otherwise({redirectTo : '/cat/catalog/index'});
99 })
100
101
102 /**
103  * */
104 .controller('CatalogRecordRetrieve',
105        ['$scope','$routeParams','$location','$q','egCore',
106 function($scope , $routeParams , $location , $q , egCore ) {
107
108     $scope.focusMe = true;
109
110     // jump to the patron checkout UI
111     function loadRecord(record_id) {
112         $location
113         .path('/cat/catalog/record/' + record_id);
114     }
115
116     $scope.submitId = function(args) {
117         $scope.recordNotFound = null;
118         if (!args.record_id) return;
119
120         // blur so next time it's set to true it will re-apply select()
121         $scope.selectMe = false;
122
123         return loadRecord(args.record_id);
124     }
125
126     $scope.submitTCN = function(args) {
127         $scope.recordNotFound = null;
128         $scope.moreRecordsFound = null;
129         if (!args.record_tcn) return;
130
131         // blur so next time it's set to true it will re-apply select()
132         $scope.selectMe = false;
133
134         // lookup TCN
135         egCore.net.request(
136             'open-ils.search',
137             'open-ils.search.biblio.tcn',
138             args.record_tcn)
139
140         .then(function(resp) { // get_barcodes
141
142             if (evt = egCore.evt.parse(resp)) {
143                 alert(evt); // FIXME
144                 return;
145             }
146
147             if (!resp.count) {
148                 $scope.recordNotFound = args.record_tcn;
149                 $scope.selectMe = true;
150                 return;
151             }
152
153             if (resp.count > 1) {
154                 $scope.moreRecordsFound = args.record_tcn;
155                 $scope.selectMe = true;
156                 return;
157             }
158
159             var record_id = resp.ids[0];
160             return loadRecord(record_id);
161         });
162     }
163
164 }])
165
166 .controller('CatalogCtrl',
167        ['$scope','$routeParams','$location','$window','$q','egCore','egHolds','egCirc',
168         'egGridDataProvider','egHoldGridActions','$timeout','holdingsSvc',
169 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc, 
170          egGridDataProvider , egHoldGridActions , $timeout , holdingsSvc) {
171
172     // set record ID on page load if available...
173     $scope.record_id = $routeParams.record_id;
174
175     if ($routeParams.record_id) $scope.from_route = true;
176     else $scope.from_route = false;
177
178     // will hold a ref to the opac iframe
179     $scope.opac_iframe = null;
180     $scope.parts_iframe = null;
181
182     $scope.in_opac_call = false;
183     $scope.opac_call = function (opac_frame_function, force_opac_tab) {
184         if ($scope.opac_iframe) {
185             if (force_opac_tab) $scope.record_tab = 'catalog';
186             $scope.in_opac_call = true;
187             $scope.opac_iframe.dom.contentWindow[opac_frame_function]();
188         }
189     }
190
191     $scope.stop_unload = false;
192     $scope.$watch('stop_unload',
193         function(newVal, oldVal) {
194             if (newVal && newVal != oldVal && $scope.opac_iframe) {
195                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
196                     return 'There is unsaved data in this record.'
197                 });
198             } else {
199                 if ($scope.opac_iframe)
200                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
201             }
202         }
203     );
204
205     // Set the "last bib" cookie, if we have that
206     if ($scope.record_id)
207         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
208
209     // also set it when the iframe changes to a new record
210     $scope.handle_page = function(url) {
211
212         if (!url || url == 'about:blank') {
213             // nothing loaded.  If we already have a record ID, leave it.
214             return;
215         }
216
217         var match = url.match(/\/+opac\/+record\/+(\d+)/);
218         if (match) {
219             $scope.record_id = match[1];
220             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
221             $scope.holdings_record_id_changed($scope.record_id);
222             init_parts_url();
223         } else {
224             delete $scope.record_id;
225             $scope.from_route = false;
226         }
227
228         // child scope is executing this function, so our digest doesn't fire ... thus,
229         $scope.$apply();
230
231         if (!$scope.in_opac_call) {
232             if ($scope.record_id) {
233                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
234                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
235             } else {
236                 tab = $routeParams.record_tab || 'catalog';
237             }
238             $scope.set_record_tab(tab);
239         } else {
240             $scope.in_opac_call = false;
241         }
242     }
243
244     // xulG catalog handlers
245     $scope.handlers = { }
246
247     // ------------------------------------------------------------------
248     // Holdings
249
250     $scope.holdingsGridControls = {};
251     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
252         get : function(offset, count) {
253             return this.arrayNotifier(holdingsSvc.copies, offset, count);
254         }
255     });
256
257     // refresh the list of holdings when the record_id is changed.
258     $scope.holdings_record_id_changed = function(id) {
259         if ($scope.record_id != id) $scope.record_id = id;
260         console.log('record id changed to ' + id + ', loading new holdings');
261         holdingsSvc.fetch({
262             rid : $scope.record_id,
263             org : $scope.holdings_ou,
264             copy: $scope.holdings_show_copies,
265             vol : $scope.holdings_show_vols,
266             empty: $scope.holdings_show_empty
267         }).then(function() {
268             $scope.holdingsGridDataProvider.refresh();
269         });
270     }
271
272     // refresh the list of holdings when the filter lib is changed.
273     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
274     $scope.holdings_ou_changed = function(org) {
275         $scope.holdings_ou = org;
276         holdingsSvc.fetch({
277             rid : $scope.record_id,
278             org : $scope.holdings_ou,
279             copy: $scope.holdings_show_copies,
280             vol : $scope.holdings_show_vols,
281             empty: $scope.holdings_show_empty
282         }).then(function() {
283             $scope.holdingsGridDataProvider.refresh();
284         });
285     }
286
287     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
288         $scope[cb] = newVal;
289         egCore.hatch.setItem('cat.' + cb, newVal);
290         if (!norefresh) holdingsSvc.fetch({
291             rid : $scope.record_id,
292             org : $scope.holdings_ou,
293             copy: $scope.holdings_show_copies,
294             vol : $scope.holdings_show_vols,
295             empty: $scope.holdings_show_empty
296         }).then(function() {
297             $scope.holdingsGridDataProvider.refresh();
298         });
299     }
300
301     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
302         if (typeof x ==  'undefined') x = true;
303         $scope.holdings_cb_changed('holdings_show_vols',x,true);
304         $('#holdings_show_vols').prop('checked', x);
305     }).then(function(){
306         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
307             if (typeof x ==  'undefined') x = true;
308             $scope.holdings_cb_changed('holdings_show_copies',x,true);
309             $('#holdings_show_copies').prop('checked', x);
310         }).then(function(){
311             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
312                 if (typeof x ==  'undefined') x = true;
313                 $scope.holdings_cb_changed('holdings_show_empty',x);
314                 $('#holdings_show_empty').prop('checked', x);
315             })
316         })
317     });
318
319     $scope.vols_not_shown = function () {
320         return !$scope.holdings_show_vols;
321     }
322
323     $scope.holdings_checkbox_handler = function (item) {
324         $scope.holdings_cb_changed(item.checkbox,item.checked);
325     }
326
327     function gatherSelectedHoldingsIds () {
328         var cp_id_list = [];
329         angular.forEach(
330             $scope.holdingsGridControls.selectedItems(),
331             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
332         );
333         return cp_id_list;
334     }
335
336     function gatherSelectedRawCopies () {
337         var cp_list = [];
338         angular.forEach(
339             $scope.holdingsGridControls.selectedItems(),
340             function (item) { cp_list = cp_list.concat(item.raw) }
341         );
342         return cp_list;
343     }
344
345     function gatherSelectedVolumeIds () {
346         var cn_id_list = [];
347         angular.forEach(
348             $scope.holdingsGridControls.selectedItems(),
349             function (item) {
350                 if (cn_id_list.indexOf(item.call_number.id) == -1)
351                     cn_id_list.push(item.call_number.id)
352             }
353         );
354         return cn_id_list;
355     }
356
357     spawnHoldingsAdd = function (hide_vols,hide_copies){
358         var raw = [];
359         if (hide_vols) { // just a copy on existing volumes
360             angular.forEach(gatherSelectedVolumeIds(), function (v) {
361                 raw.push( {callnumber : v} );
362             });
363         } else {
364             angular.forEach(
365                 $scope.holdingsGridControls.selectedItems(),
366                 function (item) {
367                     raw.push({owner : item.owner_id});
368                 }
369             );
370         }
371
372         egCore.net.request(
373             'open-ils.actor',
374             'open-ils.actor.anon_cache.set_value',
375             null, 'edit-these-copies', {
376                 record_id: $scope.record_id,
377                 raw: raw,
378                 hide_vols : hide_vols,
379                 hide_copies : hide_copies
380             }
381         ).then(function(key) {
382             if (key) {
383                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
384                 $timeout(function() { $window.open(url, '_blank') });
385             } else {
386                 alert('Could not create anonymous cache key!');
387             }
388         });
389     }
390     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(false,false) }
391     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(true,false) }
392
393     spawnHoldingsEdit = function (hide_vols,hide_copies){
394         egCore.net.request(
395             'open-ils.actor',
396             'open-ils.actor.anon_cache.set_value',
397             null, 'edit-these-copies', {
398                 record_id: $scope.record_id,
399                 copies: gatherSelectedHoldingsIds(),
400                 hide_vols : hide_vols,
401                 hide_copies : hide_copies
402             }
403         ).then(function(key) {
404             if (key) {
405                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
406                 $timeout(function() { $window.open(url, '_blank') });
407             } else {
408                 alert('Could not create anonymous cache key!');
409             }
410         });
411     }
412     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
413     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
414     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
415
416     $scope.selectedHoldingsItemStatus = function (){
417         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
418         $timeout(function() { $window.open(url, '_blank') });
419     }
420
421     $scope.markVolAsItemTarget = function() {
422         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed
423             egCore.hatch.setLocalItem(
424                 'eg.cat.item_transfer_target',
425                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
426             );
427             console.log('item_transfer_dest: '+$scope.holdingsGridControls.selectedItems()[0].call_number.id);
428         }
429     }
430
431     $scope.markLibAsVolTarget = function() {
432         egCore.hatch.setLocalItem(
433             'eg.cat.volume_transfer_target',
434             $scope.holdingsGridControls.selectedItems()[0].owner_id
435         );
436         console.log('vol_transfer_dest: '+$scope.holdingsGridControls.selectedItems()[0].owner_id);
437     }
438
439     $scope.selectedHoldingsItemStatusDetail = function (){
440         angular.forEach(
441             gatherSelectedHoldingsIds(),
442             function (cid) {
443                 var url = egCore.env.basePath +
444                           'cat/item/' + cid;
445                 $timeout(function() { $window.open(url, '_blank') });
446             }
447         );
448     }
449
450     $scope.transferVolumes = function (){
451         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
452
453         if (xfer_target) {
454             egCore.net.request(
455                 'open-ils.cat',
456                 'open-ils.open-ils.cat.asset.volume.batch.transfer.override',
457                 egCore.auth.token(), {
458                     docid   : $scope.record_id,
459                     lib     : xfer_target,
460                     volumes : gatherSelectedVolumeIds()
461                 }
462             ).then(function(success) {
463                 if (success) {
464                     holdingsSvc.fetch({
465                         rid : $scope.record_id,
466                         org : $scope.holdings_ou,
467                         copy: $scope.holdings_show_copies,
468                         vol : $scope.holdings_show_vols,
469                         empty: $scope.holdings_show_empty
470                     }).then(function() {
471                         $scope.holdingsGridDataProvider.refresh();
472                     });
473                 } else {
474                     alert('Could not transfer volumes!');
475                 }
476             });
477         }
478         
479     }
480
481     $scope.transferItems = function (){
482         var xfer_target = egCore.hatch.getLocalItem('eg.cat.item_transfer_target');
483         if (xfer_target) {
484             var copy_list = gatherSelectedRawCopies();
485
486             angular.forEach(copy_list, function (cp) {
487                 cp.call_number(xfer_target);
488             });
489
490             egCore.pcrud.update(
491                 copy_list
492             ).then(function(success) {
493                 if (success) {
494                     holdingsSvc.fetch({
495                         rid : $scope.record_id,
496                         org : $scope.holdings_ou,
497                         copy: $scope.holdings_show_copies,
498                         vol : $scope.holdings_show_vols,
499                         empty: $scope.holdings_show_empty
500                     }).then(function() {
501                         $scope.holdingsGridDataProvider.refresh();
502                     });
503                 } else {
504                     alert('Could not transfer items!');
505                 }
506             });
507         }
508         
509     }
510
511     $scope.selectedHoldingsItemStatusTgrEvt = function (){
512         angular.forEach(
513             gatherSelectedHoldingsIds(),
514             function (cid) {
515                 var url = egCore.env.basePath +
516                           'cat/item/' + cid + '/triggered_events';
517                 $timeout(function() { $window.open(url, '_blank') });
518             }
519         );
520     }
521
522     $scope.selectedHoldingsItemStatusHolds = function (){
523         angular.forEach(
524             gatherSelectedHoldingsIds(),
525             function (cid) {
526                 var url = egCore.env.basePath +
527                           'cat/item/' + cid + '/holds';
528                 $timeout(function() { $window.open(url, '_blank') });
529             }
530         );
531     }
532
533     $scope.selectedHoldingsDamaged = function () {
534         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
535             holdingsSvc.fetch({
536                 rid : $scope.record_id,
537                 org : $scope.holdings_ou,
538                 copy: $scope.holdings_show_copies,
539                 vol : $scope.holdings_show_vols,
540                 empty: $scope.holdings_show_empty
541             }).then(function() {
542                 $scope.holdingsGridDataProvider.refresh();
543             });
544         });
545     }
546
547     $scope.selectedHoldingsMissing = function () {
548         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
549             holdingsSvc.fetch({
550                 rid : $scope.record_id,
551                 org : $scope.holdings_ou,
552                 copy: $scope.holdings_show_copies,
553                 vol : $scope.holdings_show_vols,
554                 empty: $scope.holdings_show_empty
555             }).then(function() {
556                 $scope.holdingsGridDataProvider.refresh();
557             });
558         });
559     }
560
561
562     // ------------------------------------------------------------------
563     // Holds 
564     var provider = egGridDataProvider.instance({});
565     $scope.hold_grid_data_provider = provider;
566     $scope.grid_actions = egHoldGridActions;
567     $scope.grid_actions.refresh = function () { provider.refresh() };
568     $scope.hold_grid_controls = {};
569
570     var hold_ids = []; // current list of holds
571     function fetchHolds(offset, count) {
572         var ids = hold_ids.slice(offset, offset + count);
573         return egHolds.fetch_holds(ids).then(null, null,
574             function(hold_data) { 
575                 return hold_data;
576             }
577         );
578     }
579
580     provider.get = function(offset, count) {
581         if ($scope.record_tab != 'holds') return $q.when();
582         var deferred = $q.defer();
583         hold_ids = []; // no caching ATM
584
585         // fetch the IDs
586         egCore.net.request(
587             'open-ils.circ',
588             'open-ils.circ.holds.retrieve_all_from_title',
589             egCore.auth.token(), $scope.record_id, 
590             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
591         ).then(
592             function(hold_data) {
593                 angular.forEach(hold_data, function(list, type) {
594                     hold_ids = hold_ids.concat(list);
595                 });
596                 fetchHolds(offset, count).then(
597                     deferred.resolve, null, deferred.notify);
598             }
599         );
600
601         return deferred.promise;
602     }
603
604     $scope.detail_view = function(action, user_data, items) {
605         if (h = items[0]) {
606             $scope.detail_hold_id = h.hold.id();
607         }
608     }
609
610     $scope.list_view = function(items) {
611          $scope.detail_hold_id = null;
612     }
613
614     // refresh the list of record holds when the pickup lib is changed.
615     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
616     $scope.pickup_ou_changed = function(org) {
617         $scope.pickup_ou = org;
618         provider.refresh();
619     }
620
621     $scope.print_holds = function() {
622         var holds = [];
623         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
624             holds.push({
625                 hold : egCore.idl.toHash(item.hold),
626                 patron_last : item.patron_last,
627                 patron_alias : item.patron_alias,
628                 patron_barcode : item.patron_barcode,
629                 copy : egCore.idl.toHash(item.copy),
630                 volume : egCore.idl.toHash(item.volume),
631                 title : item.mvr.title(),
632                 author : item.mvr.author()
633             });
634         });
635
636         egCore.print.print({
637             context : 'receipt', 
638             template : 'holds_for_bib', 
639             scope : {holds : holds}
640         });
641     }
642
643     $scope.mark_hold_transfer_dest = function() {
644         egCore.hatch.setLocalItem(
645             'eg.circ.hold.title_transfer_target', $scope.record_id);
646     }
647
648     // UI presents this option as "all holds"
649     $scope.transfer_holds_to_marked = function() {
650         var hold_ids = $scope.hold_grid_controls.allItems().map(
651             function(hold_data) {return hold_data.hold.id()});
652         egHolds.transfer_to_marked_title(hold_ids);
653     }
654
655     // ------------------------------------------------------------------
656     // Initialize the selected tab
657
658     function init_cat_url() {
659         // Set the initial catalog URL.  This only happens once.
660         // The URL is otherwise generated through user navigation.
661         if ($scope.catalog_url) return; 
662
663         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
664
665         // A record ID in the path indicates a request for the record-
666         // specific page.
667         if ($routeParams.record_id) {
668             url = url.replace(/advanced/, '/record/' + $scope.record_id);
669         }
670
671         $scope.catalog_url = url;
672     }
673
674     function init_parts_url() {
675         $scope.parts_url = $location
676             .absUrl()
677             .replace(
678                 /\/staff.*/,
679                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
680             );
681     }
682
683     $scope.set_record_tab = function(tab) {
684         $scope.record_tab = tab;
685
686         switch(tab) {
687
688             case 'monoparts':
689                 init_parts_url();
690                 break;
691
692             case 'catalog':
693                 init_cat_url();
694                 break;
695
696             case 'holds':
697                 $scope.detail_hold_record_id = $scope.record_id; 
698                 // refresh the holds grid
699                 provider.refresh();
700                 break;
701         }
702     }
703
704     $scope.set_default_record_tab = function() {
705         egCore.hatch.setLocalItem(
706             'eg.cat.default_record_tab', $scope.record_tab);
707         $timeout(function(){$scope.default_tab = $scope.record_tab});
708     }
709
710     var tab;
711     if ($scope.record_id) {
712         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
713         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
714
715     } else {
716         tab = $routeParams.record_tab || 'catalog';
717     }
718     $scope.set_record_tab(tab);
719
720 }])
721
722 .controller('AuthorityCtrl',
723        ['$scope','$routeParams','$location','$window','$q','egCore',
724 function($scope , $routeParams , $location , $window , $q , egCore) {
725
726     // set record ID on page load if available...
727     $scope.authority_id = $routeParams.authority_id;
728
729     if ($routeParams.authority_id) $scope.from_route = true;
730     else $scope.from_route = false;
731
732     $scope.stop_unload = false;
733 }])
734
735 .controller('URLVerifyCtrl',
736        ['$scope','$location',
737 function($scope , $location) {
738     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
739 }])
740
741 .controller('VandelayCtrl',
742        ['$scope','$location',
743 function($scope , $location) {
744     $scope.vandelay_url = $location.absUrl().replace(/\/staff.*/, '/vandelay/vandelay');
745 }])
746
747 .controller('ManageAuthoritiesCtrl',
748        ['$scope','$location',
749 function($scope , $location) {
750     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
751 }])
752
753 .controller('BatchEditCtrl',
754        ['$scope','$location','$routeParams',
755 function($scope , $location , $routeParams) {
756     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
757     if ($routeParams.container_type) {
758         switch ($routeParams.container_type) {
759             case 'bucket':
760                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
761                 break;
762             case 'record':
763                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
764                 break;
765         };
766     }
767 }])
768
769  
770 .filter('boolText', function(){
771     return function (v) {
772         return v == 't';
773     }
774 })
775
776 .factory('holdingsSvc', 
777        ['egCore','$q',
778 function(egCore , $q) {
779
780     var service = {
781         ongoing : false,
782         copies : [], // record search results
783         index : 0, // search grid index
784         org : null,
785         rid : null
786     };
787
788     service.flesh = {   
789         flesh : 2, 
790         flesh_fields : {
791             acp : ['status','location'],
792             acn : ['prefix','suffix','copies']
793         }
794     }
795
796     // resolved with the last received copy
797     service.fetch = function(opts) {
798         if (service.ongoing) {
799             console.log('Skipping fetch, ongoing = true');
800             return $q.when();
801         }
802
803         var rid = opts.rid;
804         var org = opts.org;
805         var copy = opts.copy;
806         var vol = opts.vol;
807         var empty = opts.empty;
808
809         if (!rid) return $q.when();
810         if (!org) return $q.when();
811
812         service.ongoing = true;
813
814         service.rid = rid;
815         service.org = org;
816         service.copies = [];
817         service.index = 0;
818
819         var org_list = egCore.org.descendants(org.id(), true);
820         console.log('Holdings fetch with: rid='+rid+' org='+org_list+' copy='+copy+' vol='+vol+' empty='+empty);
821
822         return egCore.pcrud.search(
823             'acn',
824             {record : rid, owning_lib : org_list, deleted : 'f'},
825             service.flesh
826         ).then(
827             function() { // finished
828                 service.copies = service.copies.sort(
829                     function (a, b) {
830                         function compare_array (x, y, i) {
831                             if (x[i] && y[i]) { // both have values
832                                 if (x[i] == y[i]) { // need to look deeper
833                                     return compare_array(x, y, ++i);
834                                 }
835
836                                 if (x[i] < y[i]) { // x is first
837                                     return -1;
838                                 } else if (x[i] > y[i]) { // y is first
839                                     return 1;
840                                 }
841
842                             } else { // no orgs to compare ...
843                                 if (x[i]) return -1;
844                                 if (y[i]) return 1;
845                             }
846                             return 0;
847                         }
848
849                         var owner_order = compare_array(a.owner_list, b.owner_list, 0);
850                         if (!owner_order) {
851                             // now compare on CN label
852                             if (a.call_number.label < b.call_number.label) return -1;
853                             if (a.call_number.label > b.call_number.label) return 1;
854
855                             // try copy number
856                             if (a.copy_number < b.copy_number) return -1;
857                             if (a.copy_number > b.copy_number) return 1;
858
859                             // finally, barcode
860                             if (a.barcode < b.barcode) return -1;
861                             if (a.barcode > b.barcode) return 1;
862                         }
863                         return owner_order;
864                     }
865                 );
866
867                 // create a label using just the unique part of the owner list
868                 var index = 0;
869                 var prev_owner_list;
870                 angular.forEach(service.copies, function (cp) {
871                     if (!prev_owner_list) {
872                         cp.owner_label = cp.owner_list.join(' ... ');
873                     } else {
874                         var current_owner_list = cp.owner_list.slice();
875                         while (current_owner_list[1] && prev_owner_list[1] && current_owner_list[0] == prev_owner_list[0]) {
876                             current_owner_list.shift();
877                             prev_owner_list.shift();
878                         }
879                         cp.owner_label = current_owner_list.join(' ... ');
880                     }
881
882                     cp.index = index++;
883                     prev_owner_list = cp.owner_list.slice();
884                 });
885
886                 var new_list = service.copies;
887                 if (!copy || !vol) { // collapse copy rows, supply a count instead
888
889                     index = 0;
890                     var cp_list = [];
891                     var prev_key;
892                     var current_blob = {};
893                     angular.forEach(new_list, function (cp) {
894                         if (!prev_key) {
895                             prev_key = cp.owner_list.join('') + cp.call_number.label;
896                             if (cp.barcode) current_blob.copy_count = 1;
897                             current_blob.index = index++;
898                             current_blob.id_list = cp.id_list;
899                             current_blob.raw = cp.raw;
900                             current_blob.call_number = cp.call_number;
901                             current_blob.owner_list = cp.owner_list;
902                             current_blob.owner_label = cp.owner_label;
903                             current_blob.owner_id = cp.owner_id;
904                         } else {
905                             var current_key = cp.owner_list.join('') + cp.call_number.label;
906                             if (prev_key == current_key) { // collapse into current_blob
907                                 current_blob.copy_count++;
908                                 current_blob.id_list = current_blob.id_list.concat(cp.id_list);
909                                 current_blob.raw = current_blob.raw.concat(cp.raw);
910                             } else {
911                                 current_blob.barcode = current_blob.copy_count;
912                                 cp_list.push(current_blob);
913                                 prev_key = current_key;
914                                 current_blob = {};
915                                 if (cp.barcode) current_blob.copy_count = 1;
916                                 current_blob.index = index++;
917                                 current_blob.id_list = cp.id_list;
918                                 current_blob.raw = cp.raw;
919                                 current_blob.owner_label = cp.owner_label;
920                                 current_blob.owner_id = cp.owner_id;
921                                 current_blob.call_number = cp.call_number;
922                                 current_blob.owner_list = cp.owner_list;
923                             }
924                         }
925                     });
926
927                     current_blob.barcode = current_blob.copy_count;
928                     cp_list.push(current_blob);
929                     new_list = cp_list;
930
931                     if (!vol) { // do the same for vol rows
932
933                         index = 0;
934                         var cn_list = [];
935                         prev_key = '';
936                         var current_blob = {};
937                         angular.forEach(cp_list, function (cp) {
938                             if (!prev_key) {
939                                 prev_key = cp.owner_list.join('');
940                                 current_blob.index = index++;
941                                 current_blob.id_list = cp.id_list;
942                                 current_blob.raw = cp.raw;
943                                 current_blob.cn_count = 1;
944                                 current_blob.copy_count = cp.copy_count;
945                                 current_blob.owner_list = cp.owner_list;
946                                 current_blob.owner_label = cp.owner_label;
947                                 current_blob.owner_id = cp.owner_id;
948                             } else {
949                                 var current_key = cp.owner_list.join('');
950                                 if (prev_key == current_key) { // collapse into current_blob
951                                     current_blob.cn_count++;
952                                     current_blob.copy_count += cp.copy_count;
953                                     current_blob.id_list = current_blob.id_list.concat(cp.id_list);
954                                     current_blob.raw = current_blob.raw.concat(cp.raw);
955                                 } else {
956                                     current_blob.barcode = current_blob.copy_count;
957                                     current_blob.call_number = { label : current_blob.cn_count };
958                                     cn_list.push(current_blob);
959                                     prev_key = current_key;
960                                     current_blob = {};
961                                     current_blob.index = index++;
962                                     current_blob.id_list = cp.id_list;
963                                     current_blob.raw = cp.raw;
964                                     current_blob.owner_label = cp.owner_label;
965                                     current_blob.owner_id = cp.owner_id;
966                                     current_blob.cn_count = 1;
967                                     current_blob.copy_count = cp.copy_count;
968                                     current_blob.owner_list = cp.owner_list;
969                                 }
970                             }
971                         });
972     
973                         current_blob.barcode = current_blob.copy_count;
974                         current_blob.call_number = { label : current_blob.cn_count };
975                         cn_list.push(current_blob);
976                         new_list = cn_list;
977     
978                     }
979                 }
980
981                 service.copies = new_list;
982                 service.ongoing = false;
983             },
984
985             null, // error
986
987             // notify reads the stream of copies, one at a time.
988             function(cn) {
989
990                 var copies = cn.copies();
991                 cn.copies([]);
992
993                 angular.forEach(copies, function (cp) {
994                     cp.call_number(cn);
995                 });
996
997                 var owner_id = cn.owning_lib();
998                 var owner = egCore.org.get(owner_id);
999
1000                 var owner_name_list = [];
1001                 while (owner.parent_ou()) { // we're going to skip the top of the tree...
1002                     owner_name_list.unshift(owner.name());
1003                     owner = egCore.org.get(owner.parent_ou());
1004                 }
1005
1006                 if (copies[0]) {
1007                     var flat = [];
1008                     angular.forEach(copies, function (cp) {
1009                         var flat_cp = egCore.idl.toHash(cp);
1010                         flat_cp.owner_id = owner_id;
1011                         flat_cp.owner_list = owner_name_list;
1012                         flat_cp.id_list = [flat_cp.id];
1013                         flat_cp.raw = [cp];
1014                         flat.push(flat_cp);
1015                     });
1016
1017                     service.copies = service.copies.concat(flat);
1018                 } else if (empty) {
1019                     service.copies.push({
1020                         owner_id   : owner_id,
1021                         owner_list : owner_name_list,
1022                         call_number: egCore.idl.toHash(cn)
1023                     });
1024                 }
1025
1026                 return cn;
1027             }
1028         );
1029     }
1030
1031     return service;
1032 }])
1033
1034