]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/catalog/app.js
webstaff: Add modal "request items" to holding view
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / catalog / app.js
1 /**
2  * TPAC Frame App
3  *
4  * currently, this app doesn't use routes for each sub-ui, because 
5  * reloading the catalog each time is sloooow.  better so far to 
6  * swap out divs w/ ng-if / ng-show / ng-hide as needed.
7  *
8  */
9
10 angular.module('egCatalogApp', ['ui.bootstrap','ngRoute','egCoreMod','egGridMod', 'egMarcMod', 'egUserMod'])
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     egCore.hatch.getItem('cat.default_bib_marc_template').then(function(template) {
194         $scope.template_name = template;
195     });
196
197     $scope.loadTemplate = function() {
198         if ($scope.template_name) {
199             egCore.net.request(
200                 'open-ils.cat',
201                 'open-ils.cat.biblio.marc_template.retrieve',
202                 $scope.template_name
203             ).then(function(template) {
204                 $scope.marc_template = template;
205                 $scope.have_template = true;
206             });
207         }
208     }
209
210     $scope.setDefaultTemplate = function() {
211         var hatch_key = "cat.default_bib_marc_template";
212         if ($scope.template_name) {
213             egCore.hatch.setItem(hatch_key, $scope.template_name);
214         } else {
215             egCore.hatch.removeItem(hatch_key);
216         }
217     }
218
219     $scope.$watch('new_bib_id', function(newVal, oldVal) {
220         if (newVal) {
221             $location.path('/cat/catalog/record/' + $scope.new_bib_id);
222         }
223     });
224     
225
226 }])
227
228 .controller('CatalogCtrl',
229        ['$scope','$routeParams','$location','$window','$q','egCore','egHolds','egCirc',
230         'egGridDataProvider','egHoldGridActions','$timeout','$modal','holdingsSvc','egUser',
231 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc, 
232          egGridDataProvider , egHoldGridActions , $timeout , $modal , holdingsSvc , egUser) {
233
234     // set record ID on page load if available...
235     $scope.record_id = $routeParams.record_id;
236
237     if ($routeParams.record_id) $scope.from_route = true;
238     else $scope.from_route = false;
239
240     // will hold a ref to the opac iframe
241     $scope.opac_iframe = null;
242     $scope.parts_iframe = null;
243
244     $scope.in_opac_call = false;
245     $scope.opac_call = function (opac_frame_function, force_opac_tab) {
246         if ($scope.opac_iframe) {
247             if (force_opac_tab) $scope.record_tab = 'catalog';
248             $scope.in_opac_call = true;
249             $scope.opac_iframe.dom.contentWindow[opac_frame_function]();
250         }
251     }
252
253     $scope.stop_unload = false;
254     $scope.$watch('stop_unload',
255         function(newVal, oldVal) {
256             if (newVal && newVal != oldVal && $scope.opac_iframe) {
257                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
258                     return 'There is unsaved data in this record.'
259                 });
260             } else {
261                 if ($scope.opac_iframe)
262                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
263             }
264         }
265     );
266
267     // Set the "last bib" cookie, if we have that
268     if ($scope.record_id)
269         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
270
271     // also set it when the iframe changes to a new record
272     $scope.handle_page = function(url) {
273
274         if (!url || url == 'about:blank') {
275             // nothing loaded.  If we already have a record ID, leave it.
276             return;
277         }
278
279         var match = url.match(/\/+opac\/+record\/+(\d+)/);
280         if (match) {
281             $scope.record_id = match[1];
282             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
283             $scope.holdings_record_id_changed($scope.record_id);
284             init_parts_url();
285         } else {
286             delete $scope.record_id;
287             $scope.from_route = false;
288         }
289
290         // child scope is executing this function, so our digest doesn't fire ... thus,
291         $scope.$apply();
292
293         if (!$scope.in_opac_call) {
294             if ($scope.record_id) {
295                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
296                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
297             } else {
298                 tab = $routeParams.record_tab || 'catalog';
299             }
300             $scope.set_record_tab(tab);
301         } else {
302             $scope.in_opac_call = false;
303         }
304     }
305
306     // xulG catalog handlers
307     $scope.handlers = { }
308
309     // ------------------------------------------------------------------
310     // Holdings
311
312     $scope.holdingsGridControls = {};
313     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
314         get : function(offset, count) {
315             return this.arrayNotifier(holdingsSvc.copies, offset, count);
316         }
317     });
318
319     $scope.requestItems = function() {
320         var copy_list = gatherSelectedHoldingsIds();
321         if (copy_list.length == 0) return;
322
323         return $modal.open({
324             templateUrl: './cat/catalog/t_request_items',
325             animation: true,
326             controller:
327                    ['$scope','$modalInstance',
328             function($scope , $modalInstance) {
329                 $scope.user = null;
330                 $scope.first_user_fetch = true;
331
332                 $scope.hold_data = {
333                     hold_type : 'C',
334                     copy_list : copy_list,
335                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
336                     user      : egCore.auth.user().id()
337                 };
338
339                 egUser.get( $scope.hold_data.user ).then(function(u) {
340                     $scope.user = u;
341                     $scope.barcode = u.card().barcode();
342                     $scope.user_name = egUser.format_name(u);
343                     $scope.hold_data.user = u.id();
344                 });
345
346                 $scope.user_name = '';
347                 $scope.barcode = '';
348                 $scope.$watch('barcode', function (n) {
349                     if (!$scope.first_user_fetch) {
350                         egUser.getByBarcode(n).then(function(u) {
351                             $scope.user = u;
352                             $scope.user_name = egUser.format_name(u);
353                             $scope.hold_data.user = u.id();
354                         }, function() {
355                             $scope.user = null;
356                             $scope.user_name = '';
357                             delete $scope.hold_data.user;
358                         });
359                     }
360                     $scope.first_user_fetch = false;
361                 });
362
363                 $scope.ok = function(h) {
364                     var args = {
365                         patronid  : h.user,
366                         hold_type : h.hold_type,
367                         pickup_lib: h.pickup_lib.id(),
368                         depth     : 0
369                     };
370
371                     egCore.net.request(
372                         'open-ils.circ',
373                         'open-ils.circ.holds.test_and_create.batch.override',
374                         egCore.auth.token(), args, h.copy_list
375                     );
376
377                     $modalInstance.close();
378                 }
379
380                 $scope.cancel = function($event) {
381                     $modalInstance.dismiss();
382                     $event.preventDefault();
383                 }
384             }]
385         });
386     }
387
388     // refresh the list of holdings when the record_id is changed.
389     $scope.holdings_record_id_changed = function(id) {
390         if ($scope.record_id != id) $scope.record_id = id;
391         console.log('record id changed to ' + id + ', loading new holdings');
392         holdingsSvc.fetch({
393             rid : $scope.record_id,
394             org : $scope.holdings_ou,
395             copy: $scope.holdings_show_copies,
396             vol : $scope.holdings_show_vols,
397             empty: $scope.holdings_show_empty
398         }).then(function() {
399             $scope.holdingsGridDataProvider.refresh();
400         });
401     }
402
403     // refresh the list of holdings when the filter lib is changed.
404     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
405     $scope.holdings_ou_changed = function(org) {
406         $scope.holdings_ou = org;
407         holdingsSvc.fetch({
408             rid : $scope.record_id,
409             org : $scope.holdings_ou,
410             copy: $scope.holdings_show_copies,
411             vol : $scope.holdings_show_vols,
412             empty: $scope.holdings_show_empty
413         }).then(function() {
414             $scope.holdingsGridDataProvider.refresh();
415         });
416     }
417
418     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
419         $scope[cb] = newVal;
420         egCore.hatch.setItem('cat.' + cb, newVal);
421         if (!norefresh) holdingsSvc.fetch({
422             rid : $scope.record_id,
423             org : $scope.holdings_ou,
424             copy: $scope.holdings_show_copies,
425             vol : $scope.holdings_show_vols,
426             empty: $scope.holdings_show_empty
427         }).then(function() {
428             $scope.holdingsGridDataProvider.refresh();
429         });
430     }
431
432     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
433         if (typeof x ==  'undefined') x = true;
434         $scope.holdings_cb_changed('holdings_show_vols',x,true);
435         $('#holdings_show_vols').prop('checked', x);
436     }).then(function(){
437         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
438             if (typeof x ==  'undefined') x = true;
439             $scope.holdings_cb_changed('holdings_show_copies',x,true);
440             $('#holdings_show_copies').prop('checked', x);
441         }).then(function(){
442             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
443                 if (typeof x ==  'undefined') x = true;
444                 $scope.holdings_cb_changed('holdings_show_empty',x);
445                 $('#holdings_show_empty').prop('checked', x);
446             })
447         })
448     });
449
450     $scope.vols_not_shown = function () {
451         return !$scope.holdings_show_vols;
452     }
453
454     $scope.holdings_checkbox_handler = function (item) {
455         $scope.holdings_cb_changed(item.checkbox,item.checked);
456     }
457
458     function gatherSelectedHoldingsIds () {
459         var cp_id_list = [];
460         angular.forEach(
461             $scope.holdingsGridControls.selectedItems(),
462             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
463         );
464         return cp_id_list;
465     }
466
467     function gatherSelectedRawCopies () {
468         var cp_list = [];
469         angular.forEach(
470             $scope.holdingsGridControls.selectedItems(),
471             function (item) { cp_list = cp_list.concat(item.raw) }
472         );
473         return cp_list;
474     }
475
476     function gatherSelectedVolumeIds () {
477         var cn_id_list = [];
478         angular.forEach(
479             $scope.holdingsGridControls.selectedItems(),
480             function (item) {
481                 if (cn_id_list.indexOf(item.call_number.id) == -1)
482                     cn_id_list.push(item.call_number.id)
483             }
484         );
485         return cn_id_list;
486     }
487
488     spawnHoldingsAdd = function (hide_vols,hide_copies){
489         var raw = [];
490         if (hide_vols) { // just a copy on existing volumes
491             angular.forEach(gatherSelectedVolumeIds(), function (v) {
492                 raw.push( {callnumber : v} );
493             });
494         } else {
495             angular.forEach(
496                 $scope.holdingsGridControls.selectedItems(),
497                 function (item) {
498                     raw.push({owner : item.owner_id});
499                 }
500             );
501         }
502
503         egCore.net.request(
504             'open-ils.actor',
505             'open-ils.actor.anon_cache.set_value',
506             null, 'edit-these-copies', {
507                 record_id: $scope.record_id,
508                 raw: raw,
509                 hide_vols : hide_vols,
510                 hide_copies : hide_copies
511             }
512         ).then(function(key) {
513             if (key) {
514                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
515                 $timeout(function() { $window.open(url, '_blank') });
516             } else {
517                 alert('Could not create anonymous cache key!');
518             }
519         });
520     }
521     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(false,false) }
522     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(true,false) }
523
524     spawnHoldingsEdit = function (hide_vols,hide_copies){
525         egCore.net.request(
526             'open-ils.actor',
527             'open-ils.actor.anon_cache.set_value',
528             null, 'edit-these-copies', {
529                 record_id: $scope.record_id,
530                 copies: gatherSelectedHoldingsIds(),
531                 hide_vols : hide_vols,
532                 hide_copies : hide_copies
533             }
534         ).then(function(key) {
535             if (key) {
536                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
537                 $timeout(function() { $window.open(url, '_blank') });
538             } else {
539                 alert('Could not create anonymous cache key!');
540             }
541         });
542     }
543     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
544     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
545     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
546
547     $scope.selectedHoldingsItemStatus = function (){
548         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
549         $timeout(function() { $window.open(url, '_blank') });
550     }
551
552     $scope.markVolAsItemTarget = function() {
553         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed
554             egCore.hatch.setLocalItem(
555                 'eg.cat.item_transfer_target',
556                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
557             );
558         }
559     }
560
561     $scope.markLibAsVolTarget = function() {
562         egCore.hatch.setLocalItem(
563             'eg.cat.volume_transfer_target',
564             $scope.holdingsGridControls.selectedItems()[0].owner_id
565         );
566     }
567
568     $scope.selectedHoldingsItemStatusDetail = function (){
569         angular.forEach(
570             gatherSelectedHoldingsIds(),
571             function (cid) {
572                 var url = egCore.env.basePath +
573                           'cat/item/' + cid;
574                 $timeout(function() { $window.open(url, '_blank') });
575             }
576         );
577     }
578
579     $scope.transferVolumes = function (){
580         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
581
582         if (xfer_target) {
583             egCore.net.request(
584                 'open-ils.cat',
585                 'open-ils.open-ils.cat.asset.volume.batch.transfer.override',
586                 egCore.auth.token(), {
587                     docid   : $scope.record_id,
588                     lib     : xfer_target,
589                     volumes : gatherSelectedVolumeIds()
590                 }
591             ).then(function(success) {
592                 if (success) {
593                     holdingsSvc.fetch({
594                         rid : $scope.record_id,
595                         org : $scope.holdings_ou,
596                         copy: $scope.holdings_show_copies,
597                         vol : $scope.holdings_show_vols,
598                         empty: $scope.holdings_show_empty
599                     }).then(function() {
600                         $scope.holdingsGridDataProvider.refresh();
601                     });
602                 } else {
603                     alert('Could not transfer volumes!');
604                 }
605             });
606         }
607         
608     }
609
610     $scope.transferItems = function (){
611         var xfer_target = egCore.hatch.getLocalItem('eg.cat.item_transfer_target');
612         if (xfer_target) {
613             var copy_list = gatherSelectedRawCopies();
614
615             angular.forEach(copy_list, function (cp) {
616                 cp.call_number(xfer_target);
617             });
618
619             egCore.pcrud.update(
620                 copy_list
621             ).then(function(success) {
622                 if (success) {
623                     holdingsSvc.fetch({
624                         rid : $scope.record_id,
625                         org : $scope.holdings_ou,
626                         copy: $scope.holdings_show_copies,
627                         vol : $scope.holdings_show_vols,
628                         empty: $scope.holdings_show_empty
629                     }).then(function() {
630                         $scope.holdingsGridDataProvider.refresh();
631                     });
632                 } else {
633                     alert('Could not transfer items!');
634                 }
635             });
636         }
637         
638     }
639
640     $scope.selectedHoldingsItemStatusTgrEvt = function (){
641         angular.forEach(
642             gatherSelectedHoldingsIds(),
643             function (cid) {
644                 var url = egCore.env.basePath +
645                           'cat/item/' + cid + '/triggered_events';
646                 $timeout(function() { $window.open(url, '_blank') });
647             }
648         );
649     }
650
651     $scope.selectedHoldingsItemStatusHolds = function (){
652         angular.forEach(
653             gatherSelectedHoldingsIds(),
654             function (cid) {
655                 var url = egCore.env.basePath +
656                           'cat/item/' + cid + '/holds';
657                 $timeout(function() { $window.open(url, '_blank') });
658             }
659         );
660     }
661
662     $scope.selectedHoldingsDamaged = function () {
663         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
664             holdingsSvc.fetch({
665                 rid : $scope.record_id,
666                 org : $scope.holdings_ou,
667                 copy: $scope.holdings_show_copies,
668                 vol : $scope.holdings_show_vols,
669                 empty: $scope.holdings_show_empty
670             }).then(function() {
671                 $scope.holdingsGridDataProvider.refresh();
672             });
673         });
674     }
675
676     $scope.selectedHoldingsMissing = function () {
677         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
678             holdingsSvc.fetch({
679                 rid : $scope.record_id,
680                 org : $scope.holdings_ou,
681                 copy: $scope.holdings_show_copies,
682                 vol : $scope.holdings_show_vols,
683                 empty: $scope.holdings_show_empty
684             }).then(function() {
685                 $scope.holdingsGridDataProvider.refresh();
686             });
687         });
688     }
689
690
691     // ------------------------------------------------------------------
692     // Holds 
693     var provider = egGridDataProvider.instance({});
694     $scope.hold_grid_data_provider = provider;
695     $scope.grid_actions = egHoldGridActions;
696     $scope.grid_actions.refresh = function () { provider.refresh() };
697     $scope.hold_grid_controls = {};
698
699     var hold_ids = []; // current list of holds
700     function fetchHolds(offset, count) {
701         var ids = hold_ids.slice(offset, offset + count);
702         return egHolds.fetch_holds(ids).then(null, null,
703             function(hold_data) { 
704                 return hold_data;
705             }
706         );
707     }
708
709     provider.get = function(offset, count) {
710         if ($scope.record_tab != 'holds') return $q.when();
711         var deferred = $q.defer();
712         hold_ids = []; // no caching ATM
713
714         // fetch the IDs
715         egCore.net.request(
716             'open-ils.circ',
717             'open-ils.circ.holds.retrieve_all_from_title',
718             egCore.auth.token(), $scope.record_id, 
719             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
720         ).then(
721             function(hold_data) {
722                 angular.forEach(hold_data, function(list, type) {
723                     hold_ids = hold_ids.concat(list);
724                 });
725                 fetchHolds(offset, count).then(
726                     deferred.resolve, null, deferred.notify);
727             }
728         );
729
730         return deferred.promise;
731     }
732
733     $scope.detail_view = function(action, user_data, items) {
734         if (h = items[0]) {
735             $scope.detail_hold_id = h.hold.id();
736         }
737     }
738
739     $scope.list_view = function(items) {
740          $scope.detail_hold_id = null;
741     }
742
743     // refresh the list of record holds when the pickup lib is changed.
744     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
745     $scope.pickup_ou_changed = function(org) {
746         $scope.pickup_ou = org;
747         provider.refresh();
748     }
749
750     $scope.print_holds = function() {
751         var holds = [];
752         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
753             holds.push({
754                 hold : egCore.idl.toHash(item.hold),
755                 patron_last : item.patron_last,
756                 patron_alias : item.patron_alias,
757                 patron_barcode : item.patron_barcode,
758                 copy : egCore.idl.toHash(item.copy),
759                 volume : egCore.idl.toHash(item.volume),
760                 title : item.mvr.title(),
761                 author : item.mvr.author()
762             });
763         });
764
765         egCore.print.print({
766             context : 'receipt', 
767             template : 'holds_for_bib', 
768             scope : {holds : holds}
769         });
770     }
771
772     $scope.mark_hold_transfer_dest = function() {
773         egCore.hatch.setLocalItem(
774             'eg.circ.hold.title_transfer_target', $scope.record_id);
775     }
776
777     // UI presents this option as "all holds"
778     $scope.transfer_holds_to_marked = function() {
779         var hold_ids = $scope.hold_grid_controls.allItems().map(
780             function(hold_data) {return hold_data.hold.id()});
781         egHolds.transfer_to_marked_title(hold_ids);
782     }
783
784     // ------------------------------------------------------------------
785     // Initialize the selected tab
786
787     function init_cat_url() {
788         // Set the initial catalog URL.  This only happens once.
789         // The URL is otherwise generated through user navigation.
790         if ($scope.catalog_url) return; 
791
792         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
793
794         // A record ID in the path indicates a request for the record-
795         // specific page.
796         if ($routeParams.record_id) {
797             url = url.replace(/advanced/, '/record/' + $scope.record_id);
798         }
799
800         $scope.catalog_url = url;
801     }
802
803     function init_parts_url() {
804         $scope.parts_url = $location
805             .absUrl()
806             .replace(
807                 /\/staff.*/,
808                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
809             );
810     }
811
812     $scope.set_record_tab = function(tab) {
813         $scope.record_tab = tab;
814
815         switch(tab) {
816
817             case 'monoparts':
818                 init_parts_url();
819                 break;
820
821             case 'catalog':
822                 init_cat_url();
823                 break;
824
825             case 'holds':
826                 $scope.detail_hold_record_id = $scope.record_id; 
827                 // refresh the holds grid
828                 provider.refresh();
829                 break;
830         }
831     }
832
833     $scope.set_default_record_tab = function() {
834         egCore.hatch.setLocalItem(
835             'eg.cat.default_record_tab', $scope.record_tab);
836         $timeout(function(){$scope.default_tab = $scope.record_tab});
837     }
838
839     var tab;
840     if ($scope.record_id) {
841         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
842         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
843
844     } else {
845         tab = $routeParams.record_tab || 'catalog';
846     }
847     $scope.set_record_tab(tab);
848
849 }])
850
851 .controller('AuthorityCtrl',
852        ['$scope','$routeParams','$location','$window','$q','egCore',
853 function($scope , $routeParams , $location , $window , $q , egCore) {
854
855     // set record ID on page load if available...
856     $scope.authority_id = $routeParams.authority_id;
857
858     if ($routeParams.authority_id) $scope.from_route = true;
859     else $scope.from_route = false;
860
861     $scope.stop_unload = false;
862 }])
863
864 .controller('URLVerifyCtrl',
865        ['$scope','$location',
866 function($scope , $location) {
867     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
868 }])
869
870 .controller('VandelayCtrl',
871        ['$scope','$location',
872 function($scope , $location) {
873     $scope.vandelay_url = $location.absUrl().replace(/\/staff.*/, '/vandelay/vandelay');
874 }])
875
876 .controller('ManageAuthoritiesCtrl',
877        ['$scope','$location',
878 function($scope , $location) {
879     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
880 }])
881
882 .controller('BatchEditCtrl',
883        ['$scope','$location','$routeParams',
884 function($scope , $location , $routeParams) {
885     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
886     if ($routeParams.container_type) {
887         switch ($routeParams.container_type) {
888             case 'bucket':
889                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
890                 break;
891             case 'record':
892                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
893                 break;
894         };
895     }
896 }])
897
898  
899 .filter('boolText', function(){
900     return function (v) {
901         return v == 't';
902     }
903 })
904
905 .factory('holdingsSvc', 
906        ['egCore','$q',
907 function(egCore , $q) {
908
909     var service = {
910         ongoing : false,
911         copies : [], // record search results
912         index : 0, // search grid index
913         org : null,
914         rid : null
915     };
916
917     service.flesh = {   
918         flesh : 2, 
919         flesh_fields : {
920             acp : ['status','location'],
921             acn : ['prefix','suffix','copies']
922         }
923     }
924
925     // resolved with the last received copy
926     service.fetch = function(opts) {
927         if (service.ongoing) {
928             console.log('Skipping fetch, ongoing = true');
929             return $q.when();
930         }
931
932         var rid = opts.rid;
933         var org = opts.org;
934         var copy = opts.copy;
935         var vol = opts.vol;
936         var empty = opts.empty;
937
938         if (!rid) return $q.when();
939         if (!org) return $q.when();
940
941         service.ongoing = true;
942
943         service.rid = rid;
944         service.org = org;
945         service.copies = [];
946         service.index = 0;
947
948         var org_list = egCore.org.descendants(org.id(), true);
949         console.log('Holdings fetch with: rid='+rid+' org='+org_list+' copy='+copy+' vol='+vol+' empty='+empty);
950
951         return egCore.pcrud.search(
952             'acn',
953             {record : rid, owning_lib : org_list, deleted : 'f'},
954             service.flesh
955         ).then(
956             function() { // finished
957                 service.copies = service.copies.sort(
958                     function (a, b) {
959                         function compare_array (x, y, i) {
960                             if (x[i] && y[i]) { // both have values
961                                 if (x[i] == y[i]) { // need to look deeper
962                                     return compare_array(x, y, ++i);
963                                 }
964
965                                 if (x[i] < y[i]) { // x is first
966                                     return -1;
967                                 } else if (x[i] > y[i]) { // y is first
968                                     return 1;
969                                 }
970
971                             } else { // no orgs to compare ...
972                                 if (x[i]) return -1;
973                                 if (y[i]) return 1;
974                             }
975                             return 0;
976                         }
977
978                         var owner_order = compare_array(a.owner_list, b.owner_list, 0);
979                         if (!owner_order) {
980                             // now compare on CN label
981                             if (a.call_number.label < b.call_number.label) return -1;
982                             if (a.call_number.label > b.call_number.label) return 1;
983
984                             // try copy number
985                             if (a.copy_number < b.copy_number) return -1;
986                             if (a.copy_number > b.copy_number) return 1;
987
988                             // finally, barcode
989                             if (a.barcode < b.barcode) return -1;
990                             if (a.barcode > b.barcode) return 1;
991                         }
992                         return owner_order;
993                     }
994                 );
995
996                 // create a label using just the unique part of the owner list
997                 var index = 0;
998                 var prev_owner_list;
999                 angular.forEach(service.copies, function (cp) {
1000                     if (!prev_owner_list) {
1001                         cp.owner_label = cp.owner_list.join(' ... ');
1002                     } else {
1003                         var current_owner_list = cp.owner_list.slice();
1004                         while (current_owner_list[1] && prev_owner_list[1] && current_owner_list[0] == prev_owner_list[0]) {
1005                             current_owner_list.shift();
1006                             prev_owner_list.shift();
1007                         }
1008                         cp.owner_label = current_owner_list.join(' ... ');
1009                     }
1010
1011                     cp.index = index++;
1012                     prev_owner_list = cp.owner_list.slice();
1013                 });
1014
1015                 var new_list = service.copies;
1016                 if (!copy || !vol) { // collapse copy rows, supply a count instead
1017
1018                     index = 0;
1019                     var cp_list = [];
1020                     var prev_key;
1021                     var current_blob = {};
1022                     angular.forEach(new_list, function (cp) {
1023                         if (!prev_key) {
1024                             prev_key = cp.owner_list.join('') + cp.call_number.label;
1025                             if (cp.barcode) current_blob.copy_count = 1;
1026                             current_blob.index = index++;
1027                             current_blob.id_list = cp.id_list;
1028                             current_blob.raw = cp.raw;
1029                             current_blob.call_number = cp.call_number;
1030                             current_blob.owner_list = cp.owner_list;
1031                             current_blob.owner_label = cp.owner_label;
1032                             current_blob.owner_id = cp.owner_id;
1033                         } else {
1034                             var current_key = cp.owner_list.join('') + cp.call_number.label;
1035                             if (prev_key == current_key) { // collapse into current_blob
1036                                 current_blob.copy_count++;
1037                                 current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1038                                 current_blob.raw = current_blob.raw.concat(cp.raw);
1039                             } else {
1040                                 current_blob.barcode = current_blob.copy_count;
1041                                 cp_list.push(current_blob);
1042                                 prev_key = current_key;
1043                                 current_blob = {};
1044                                 if (cp.barcode) current_blob.copy_count = 1;
1045                                 current_blob.index = index++;
1046                                 current_blob.id_list = cp.id_list;
1047                                 current_blob.raw = cp.raw;
1048                                 current_blob.owner_label = cp.owner_label;
1049                                 current_blob.owner_id = cp.owner_id;
1050                                 current_blob.call_number = cp.call_number;
1051                                 current_blob.owner_list = cp.owner_list;
1052                             }
1053                         }
1054                     });
1055
1056                     current_blob.barcode = current_blob.copy_count;
1057                     cp_list.push(current_blob);
1058                     new_list = cp_list;
1059
1060                     if (!vol) { // do the same for vol rows
1061
1062                         index = 0;
1063                         var cn_list = [];
1064                         prev_key = '';
1065                         var current_blob = {};
1066                         angular.forEach(cp_list, function (cp) {
1067                             if (!prev_key) {
1068                                 prev_key = cp.owner_list.join('');
1069                                 current_blob.index = index++;
1070                                 current_blob.id_list = cp.id_list;
1071                                 current_blob.raw = cp.raw;
1072                                 current_blob.cn_count = 1;
1073                                 current_blob.copy_count = cp.copy_count;
1074                                 current_blob.owner_list = cp.owner_list;
1075                                 current_blob.owner_label = cp.owner_label;
1076                                 current_blob.owner_id = cp.owner_id;
1077                             } else {
1078                                 var current_key = cp.owner_list.join('');
1079                                 if (prev_key == current_key) { // collapse into current_blob
1080                                     current_blob.cn_count++;
1081                                     current_blob.copy_count += cp.copy_count;
1082                                     current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1083                                     current_blob.raw = current_blob.raw.concat(cp.raw);
1084                                 } else {
1085                                     current_blob.barcode = current_blob.copy_count;
1086                                     current_blob.call_number = { label : current_blob.cn_count };
1087                                     cn_list.push(current_blob);
1088                                     prev_key = current_key;
1089                                     current_blob = {};
1090                                     current_blob.index = index++;
1091                                     current_blob.id_list = cp.id_list;
1092                                     current_blob.raw = cp.raw;
1093                                     current_blob.owner_label = cp.owner_label;
1094                                     current_blob.owner_id = cp.owner_id;
1095                                     current_blob.cn_count = 1;
1096                                     current_blob.copy_count = cp.copy_count;
1097                                     current_blob.owner_list = cp.owner_list;
1098                                 }
1099                             }
1100                         });
1101     
1102                         current_blob.barcode = current_blob.copy_count;
1103                         current_blob.call_number = { label : current_blob.cn_count };
1104                         cn_list.push(current_blob);
1105                         new_list = cn_list;
1106     
1107                     }
1108                 }
1109
1110                 service.copies = new_list;
1111                 service.ongoing = false;
1112             },
1113
1114             null, // error
1115
1116             // notify reads the stream of copies, one at a time.
1117             function(cn) {
1118
1119                 var copies = cn.copies();
1120                 cn.copies([]);
1121
1122                 angular.forEach(copies, function (cp) {
1123                     cp.call_number(cn);
1124                 });
1125
1126                 var owner_id = cn.owning_lib();
1127                 var owner = egCore.org.get(owner_id);
1128
1129                 var owner_name_list = [];
1130                 while (owner.parent_ou()) { // we're going to skip the top of the tree...
1131                     owner_name_list.unshift(owner.name());
1132                     owner = egCore.org.get(owner.parent_ou());
1133                 }
1134
1135                 if (copies[0]) {
1136                     var flat = [];
1137                     angular.forEach(copies, function (cp) {
1138                         var flat_cp = egCore.idl.toHash(cp);
1139                         flat_cp.owner_id = owner_id;
1140                         flat_cp.owner_list = owner_name_list;
1141                         flat_cp.id_list = [flat_cp.id];
1142                         flat_cp.raw = [cp];
1143                         flat.push(flat_cp);
1144                     });
1145
1146                     service.copies = service.copies.concat(flat);
1147                 } else if (empty) {
1148                     service.copies.push({
1149                         owner_id   : owner_id,
1150                         owner_list : owner_name_list,
1151                         call_number: egCore.idl.toHash(cn)
1152                     });
1153                 }
1154
1155                 return cn;
1156             }
1157         );
1158     }
1159
1160     return service;
1161 }])
1162
1163