]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/catalog/app.js
webstaff: Allow deleting copys/vols ... need a speed bump?
[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.copies_not_shown = function () {
455         return !$scope.holdings_show_copies;
456     }
457
458     $scope.holdings_checkbox_handler = function (item) {
459         $scope.holdings_cb_changed(item.checkbox,item.checked);
460     }
461
462     function gatherSelectedHoldingsIds () {
463         var cp_id_list = [];
464         angular.forEach(
465             $scope.holdingsGridControls.selectedItems(),
466             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
467         );
468         return cp_id_list;
469     }
470
471     function gatherSelectedRawCopies () {
472         var cp_list = [];
473         angular.forEach(
474             $scope.holdingsGridControls.selectedItems(),
475             function (item) { if (item.raw) cp_list = cp_list.concat(item.raw) }
476         );
477         return cp_list;
478     }
479
480     function gatherSelectedVolumeIds () {
481         var cn_id_list = [];
482         angular.forEach(
483             $scope.holdingsGridControls.selectedItems(),
484             function (item) {
485                 if (cn_id_list.indexOf(item.call_number.id) == -1)
486                     cn_id_list.push(item.call_number.id)
487             }
488         );
489         return cn_id_list;
490     }
491
492     $scope.selectedHoldingsDelete = function (vols, copies) {
493
494         var cnHash = {};
495         var perCnCopies = {};
496
497         angular.forEach(
498             $scope.holdingsGridControls.selectedItems(),
499             function (item) {
500                 if (vols && item.raw_call_number) {
501                     cnHash[item.call_number.id] = egCore.idl.Clone(item.raw_call_number);
502                     cnHash[item.call_number.id].isdeleted(1);
503                 } else if (copies) {
504                     angular.forEach(egCore.idl.Clone(item.raw), function (cp) {
505                         cp.isdeleted(1);
506                         var cn_id = cp.call_number().id();
507                         if (!cnHash[cn_id]) {
508                             cnHash[cn_id] = cp.call_number();
509                             perCnCopies[cn_id] = [cp];
510                         } else {
511                             perCnCopies[cn_id].push(cp);
512                         }
513                         cp.call_number(cn_id); // prevent loops in JSON-ification
514                     });
515
516                 }
517             }
518         );
519
520         angular.forEach(perCnCopies, function (v, k) {
521             if (vols) cnHash[k].isdeleted(1);
522             cnHash[k].copies(v);
523         });
524
525         cnList = [];
526         angular.forEach(cnHash, function (v, k) {
527             cnList.push(v);
528         });
529
530         if (cnList.length == 0) return;
531
532         egCore.net.request(
533             'open-ils.cat',
534             'open-ils.cat.asset.volume.fleshed.batch.update.override',
535             egCore.auth.token(), cnList, 1, {}
536         ).then(function(update_count) {
537             $scope.holdingsGridDataProvider.refresh();
538         });
539     }
540     $scope.selectedHoldingsCopyDelete = function () { $scope.selectedHoldingsDelete(false,true) }
541     $scope.selectedHoldingsVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,true) }
542     $scope.selectedHoldingsEmptyVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,false) }
543
544     spawnHoldingsAdd = function (vols,copies){
545         var raw = [];
546         if (copies) { // just a copy on existing volumes
547             angular.forEach(gatherSelectedVolumeIds(), function (v) {
548                 raw.push( {callnumber : v} );
549             });
550         } else if (vols) {
551             angular.forEach(
552                 $scope.holdingsGridControls.selectedItems(),
553                 function (item) {
554                     raw.push({owner : item.owner_id});
555                 }
556             );
557         }
558
559         egCore.net.request(
560             'open-ils.actor',
561             'open-ils.actor.anon_cache.set_value',
562             null, 'edit-these-copies', {
563                 record_id: $scope.record_id,
564                 raw: raw,
565                 hide_vols : false,
566                 hide_copies : false
567             }
568         ).then(function(key) {
569             if (key) {
570                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
571                 $timeout(function() { $window.open(url, '_blank') });
572             } else {
573                 alert('Could not create anonymous cache key!');
574             }
575         });
576     }
577     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(true,false) }
578     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(false,true) }
579
580     spawnHoldingsEdit = function (hide_vols,hide_copies){
581         egCore.net.request(
582             'open-ils.actor',
583             'open-ils.actor.anon_cache.set_value',
584             null, 'edit-these-copies', {
585                 record_id: $scope.record_id,
586                 copies: gatherSelectedHoldingsIds(),
587                 hide_vols : hide_vols,
588                 hide_copies : hide_copies
589             }
590         ).then(function(key) {
591             if (key) {
592                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
593                 $timeout(function() { $window.open(url, '_blank') });
594             } else {
595                 alert('Could not create anonymous cache key!');
596             }
597         });
598     }
599     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
600     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
601     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
602
603     $scope.selectedHoldingsItemStatus = function (){
604         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
605         $timeout(function() { $window.open(url, '_blank') });
606     }
607
608     $scope.markVolAsItemTarget = function() {
609         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed
610             egCore.hatch.setLocalItem(
611                 'eg.cat.item_transfer_target',
612                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
613             );
614         }
615     }
616
617     $scope.markLibAsVolTarget = function() {
618         egCore.hatch.setLocalItem(
619             'eg.cat.volume_transfer_target',
620             $scope.holdingsGridControls.selectedItems()[0].owner_id
621         );
622     }
623
624     $scope.selectedHoldingsItemStatusDetail = function (){
625         angular.forEach(
626             gatherSelectedHoldingsIds(),
627             function (cid) {
628                 var url = egCore.env.basePath +
629                           'cat/item/' + cid;
630                 $timeout(function() { $window.open(url, '_blank') });
631             }
632         );
633     }
634
635     $scope.transferVolumes = function (){
636         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
637
638         if (xfer_target) {
639             egCore.net.request(
640                 'open-ils.cat',
641                 'open-ils.open-ils.cat.asset.volume.batch.transfer.override',
642                 egCore.auth.token(), {
643                     docid   : $scope.record_id,
644                     lib     : xfer_target,
645                     volumes : gatherSelectedVolumeIds()
646                 }
647             ).then(function(success) {
648                 if (success) {
649                     holdingsSvc.fetch({
650                         rid : $scope.record_id,
651                         org : $scope.holdings_ou,
652                         copy: $scope.holdings_show_copies,
653                         vol : $scope.holdings_show_vols,
654                         empty: $scope.holdings_show_empty
655                     }).then(function() {
656                         $scope.holdingsGridDataProvider.refresh();
657                     });
658                 } else {
659                     alert('Could not transfer volumes!');
660                 }
661             });
662         }
663         
664     }
665
666     $scope.transferItems = function (){
667         var xfer_target = egCore.hatch.getLocalItem('eg.cat.item_transfer_target');
668         if (xfer_target) {
669             var copy_list = gatherSelectedRawCopies();
670
671             angular.forEach(copy_list, function (cp) {
672                 cp.call_number(xfer_target);
673             });
674
675             egCore.pcrud.update(
676                 copy_list
677             ).then(function(success) {
678                 if (success) {
679                     holdingsSvc.fetch({
680                         rid : $scope.record_id,
681                         org : $scope.holdings_ou,
682                         copy: $scope.holdings_show_copies,
683                         vol : $scope.holdings_show_vols,
684                         empty: $scope.holdings_show_empty
685                     }).then(function() {
686                         $scope.holdingsGridDataProvider.refresh();
687                     });
688                 } else {
689                     alert('Could not transfer items!');
690                 }
691             });
692         }
693         
694     }
695
696     $scope.selectedHoldingsItemStatusTgrEvt = function (){
697         angular.forEach(
698             gatherSelectedHoldingsIds(),
699             function (cid) {
700                 var url = egCore.env.basePath +
701                           'cat/item/' + cid + '/triggered_events';
702                 $timeout(function() { $window.open(url, '_blank') });
703             }
704         );
705     }
706
707     $scope.selectedHoldingsItemStatusHolds = function (){
708         angular.forEach(
709             gatherSelectedHoldingsIds(),
710             function (cid) {
711                 var url = egCore.env.basePath +
712                           'cat/item/' + cid + '/holds';
713                 $timeout(function() { $window.open(url, '_blank') });
714             }
715         );
716     }
717
718     $scope.selectedHoldingsDamaged = function () {
719         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
720             holdingsSvc.fetch({
721                 rid : $scope.record_id,
722                 org : $scope.holdings_ou,
723                 copy: $scope.holdings_show_copies,
724                 vol : $scope.holdings_show_vols,
725                 empty: $scope.holdings_show_empty
726             }).then(function() {
727                 $scope.holdingsGridDataProvider.refresh();
728             });
729         });
730     }
731
732     $scope.selectedHoldingsMissing = function () {
733         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
734             holdingsSvc.fetch({
735                 rid : $scope.record_id,
736                 org : $scope.holdings_ou,
737                 copy: $scope.holdings_show_copies,
738                 vol : $scope.holdings_show_vols,
739                 empty: $scope.holdings_show_empty
740             }).then(function() {
741                 $scope.holdingsGridDataProvider.refresh();
742             });
743         });
744     }
745
746
747     // ------------------------------------------------------------------
748     // Holds 
749     var provider = egGridDataProvider.instance({});
750     $scope.hold_grid_data_provider = provider;
751     $scope.grid_actions = egHoldGridActions;
752     $scope.grid_actions.refresh = function () { provider.refresh() };
753     $scope.hold_grid_controls = {};
754
755     var hold_ids = []; // current list of holds
756     function fetchHolds(offset, count) {
757         var ids = hold_ids.slice(offset, offset + count);
758         return egHolds.fetch_holds(ids).then(null, null,
759             function(hold_data) { 
760                 return hold_data;
761             }
762         );
763     }
764
765     provider.get = function(offset, count) {
766         if ($scope.record_tab != 'holds') return $q.when();
767         var deferred = $q.defer();
768         hold_ids = []; // no caching ATM
769
770         // fetch the IDs
771         egCore.net.request(
772             'open-ils.circ',
773             'open-ils.circ.holds.retrieve_all_from_title',
774             egCore.auth.token(), $scope.record_id, 
775             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
776         ).then(
777             function(hold_data) {
778                 angular.forEach(hold_data, function(list, type) {
779                     hold_ids = hold_ids.concat(list);
780                 });
781                 fetchHolds(offset, count).then(
782                     deferred.resolve, null, deferred.notify);
783             }
784         );
785
786         return deferred.promise;
787     }
788
789     $scope.detail_view = function(action, user_data, items) {
790         if (h = items[0]) {
791             $scope.detail_hold_id = h.hold.id();
792         }
793     }
794
795     $scope.list_view = function(items) {
796          $scope.detail_hold_id = null;
797     }
798
799     // refresh the list of record holds when the pickup lib is changed.
800     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
801     $scope.pickup_ou_changed = function(org) {
802         $scope.pickup_ou = org;
803         provider.refresh();
804     }
805
806     $scope.print_holds = function() {
807         var holds = [];
808         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
809             holds.push({
810                 hold : egCore.idl.toHash(item.hold),
811                 patron_last : item.patron_last,
812                 patron_alias : item.patron_alias,
813                 patron_barcode : item.patron_barcode,
814                 copy : egCore.idl.toHash(item.copy),
815                 volume : egCore.idl.toHash(item.volume),
816                 title : item.mvr.title(),
817                 author : item.mvr.author()
818             });
819         });
820
821         egCore.print.print({
822             context : 'receipt', 
823             template : 'holds_for_bib', 
824             scope : {holds : holds}
825         });
826     }
827
828     $scope.mark_hold_transfer_dest = function() {
829         egCore.hatch.setLocalItem(
830             'eg.circ.hold.title_transfer_target', $scope.record_id);
831     }
832
833     // UI presents this option as "all holds"
834     $scope.transfer_holds_to_marked = function() {
835         var hold_ids = $scope.hold_grid_controls.allItems().map(
836             function(hold_data) {return hold_data.hold.id()});
837         egHolds.transfer_to_marked_title(hold_ids);
838     }
839
840     // ------------------------------------------------------------------
841     // Initialize the selected tab
842
843     function init_cat_url() {
844         // Set the initial catalog URL.  This only happens once.
845         // The URL is otherwise generated through user navigation.
846         if ($scope.catalog_url) return; 
847
848         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
849
850         // A record ID in the path indicates a request for the record-
851         // specific page.
852         if ($routeParams.record_id) {
853             url = url.replace(/advanced/, '/record/' + $scope.record_id);
854         }
855
856         $scope.catalog_url = url;
857     }
858
859     function init_parts_url() {
860         $scope.parts_url = $location
861             .absUrl()
862             .replace(
863                 /\/staff.*/,
864                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
865             );
866     }
867
868     $scope.set_record_tab = function(tab) {
869         $scope.record_tab = tab;
870
871         switch(tab) {
872
873             case 'monoparts':
874                 init_parts_url();
875                 break;
876
877             case 'catalog':
878                 init_cat_url();
879                 break;
880
881             case 'holds':
882                 $scope.detail_hold_record_id = $scope.record_id; 
883                 // refresh the holds grid
884                 provider.refresh();
885                 break;
886         }
887     }
888
889     $scope.set_default_record_tab = function() {
890         egCore.hatch.setLocalItem(
891             'eg.cat.default_record_tab', $scope.record_tab);
892         $timeout(function(){$scope.default_tab = $scope.record_tab});
893     }
894
895     var tab;
896     if ($scope.record_id) {
897         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
898         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
899
900     } else {
901         tab = $routeParams.record_tab || 'catalog';
902     }
903     $scope.set_record_tab(tab);
904
905 }])
906
907 .controller('AuthorityCtrl',
908        ['$scope','$routeParams','$location','$window','$q','egCore',
909 function($scope , $routeParams , $location , $window , $q , egCore) {
910
911     // set record ID on page load if available...
912     $scope.authority_id = $routeParams.authority_id;
913
914     if ($routeParams.authority_id) $scope.from_route = true;
915     else $scope.from_route = false;
916
917     $scope.stop_unload = false;
918 }])
919
920 .controller('URLVerifyCtrl',
921        ['$scope','$location',
922 function($scope , $location) {
923     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
924 }])
925
926 .controller('VandelayCtrl',
927        ['$scope','$location',
928 function($scope , $location) {
929     $scope.vandelay_url = $location.absUrl().replace(/\/staff.*/, '/vandelay/vandelay');
930 }])
931
932 .controller('ManageAuthoritiesCtrl',
933        ['$scope','$location',
934 function($scope , $location) {
935     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
936 }])
937
938 .controller('BatchEditCtrl',
939        ['$scope','$location','$routeParams',
940 function($scope , $location , $routeParams) {
941     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
942     if ($routeParams.container_type) {
943         switch ($routeParams.container_type) {
944             case 'bucket':
945                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
946                 break;
947             case 'record':
948                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
949                 break;
950         };
951     }
952 }])
953
954  
955 .filter('boolText', function(){
956     return function (v) {
957         return v == 't';
958     }
959 })
960
961 .factory('holdingsSvc', 
962        ['egCore','$q',
963 function(egCore , $q) {
964
965     var service = {
966         ongoing : false,
967         copies : [], // record search results
968         index : 0, // search grid index
969         org : null,
970         rid : null
971     };
972
973     service.flesh = {   
974         flesh : 2, 
975         flesh_fields : {
976             acp : ['status','location'],
977             acn : ['prefix','suffix','copies']
978         }
979     }
980
981     // resolved with the last received copy
982     service.fetch = function(opts) {
983         if (service.ongoing) {
984             console.log('Skipping fetch, ongoing = true');
985             return $q.when();
986         }
987
988         var rid = opts.rid;
989         var org = opts.org;
990         var copy = opts.copy;
991         var vol = opts.vol;
992         var empty = opts.empty;
993
994         if (!rid) return $q.when();
995         if (!org) return $q.when();
996
997         service.ongoing = true;
998
999         service.rid = rid;
1000         service.org = org;
1001         service.copies = [];
1002         service.index = 0;
1003
1004         var org_list = egCore.org.descendants(org.id(), true);
1005         console.log('Holdings fetch with: rid='+rid+' org='+org_list+' copy='+copy+' vol='+vol+' empty='+empty);
1006
1007         return egCore.pcrud.search(
1008             'acn',
1009             {record : rid, owning_lib : org_list, deleted : 'f'},
1010             service.flesh
1011         ).then(
1012             function() { // finished
1013                 service.copies = service.copies.sort(
1014                     function (a, b) {
1015                         function compare_array (x, y, i) {
1016                             if (x[i] && y[i]) { // both have values
1017                                 if (x[i] == y[i]) { // need to look deeper
1018                                     return compare_array(x, y, ++i);
1019                                 }
1020
1021                                 if (x[i] < y[i]) { // x is first
1022                                     return -1;
1023                                 } else if (x[i] > y[i]) { // y is first
1024                                     return 1;
1025                                 }
1026
1027                             } else { // no orgs to compare ...
1028                                 if (x[i]) return -1;
1029                                 if (y[i]) return 1;
1030                             }
1031                             return 0;
1032                         }
1033
1034                         var owner_order = compare_array(a.owner_list, b.owner_list, 0);
1035                         if (!owner_order) {
1036                             // now compare on CN label
1037                             if (a.call_number.label < b.call_number.label) return -1;
1038                             if (a.call_number.label > b.call_number.label) return 1;
1039
1040                             // try copy number
1041                             if (a.copy_number < b.copy_number) return -1;
1042                             if (a.copy_number > b.copy_number) return 1;
1043
1044                             // finally, barcode
1045                             if (a.barcode < b.barcode) return -1;
1046                             if (a.barcode > b.barcode) return 1;
1047                         }
1048                         return owner_order;
1049                     }
1050                 );
1051
1052                 // create a label using just the unique part of the owner list
1053                 var index = 0;
1054                 var prev_owner_list;
1055                 angular.forEach(service.copies, function (cp) {
1056                     if (!prev_owner_list) {
1057                         cp.owner_label = cp.owner_list.join(' ... ');
1058                     } else {
1059                         var current_owner_list = cp.owner_list.slice();
1060                         while (current_owner_list[1] && prev_owner_list[1] && current_owner_list[0] == prev_owner_list[0]) {
1061                             current_owner_list.shift();
1062                             prev_owner_list.shift();
1063                         }
1064                         cp.owner_label = current_owner_list.join(' ... ');
1065                     }
1066
1067                     cp.index = index++;
1068                     prev_owner_list = cp.owner_list.slice();
1069                 });
1070
1071                 var new_list = service.copies;
1072                 if (!copy || !vol) { // collapse copy rows, supply a count instead
1073
1074                     index = 0;
1075                     var cp_list = [];
1076                     var prev_key;
1077                     var current_blob = { copy_count : 0 };
1078                     angular.forEach(new_list, function (cp) {
1079                         if (!prev_key) {
1080                             prev_key = cp.owner_list.join('') + cp.call_number.label;
1081                             if (cp.barcode) current_blob.copy_count = 1;
1082                             current_blob.index = index++;
1083                             current_blob.id_list = cp.id_list;
1084                             if (cp.raw) current_blob.raw = cp.raw;
1085                             current_blob.call_number = cp.call_number;
1086                             current_blob.owner_list = cp.owner_list;
1087                             current_blob.owner_label = cp.owner_label;
1088                             current_blob.owner_id = cp.owner_id;
1089                         } else {
1090                             var current_key = cp.owner_list.join('') + cp.call_number.label;
1091                             if (prev_key == current_key) { // collapse into current_blob
1092                                 current_blob.copy_count++;
1093                                 current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1094                                 current_blob.raw = current_blob.raw.concat(cp.raw);
1095                             } else {
1096                                 current_blob.barcode = current_blob.copy_count;
1097                                 cp_list.push(current_blob);
1098                                 prev_key = current_key;
1099                                 current_blob = { copy_count : 0 };
1100                                 if (cp.barcode) current_blob.copy_count = 1;
1101                                 current_blob.index = index++;
1102                                 current_blob.id_list = cp.id_list;
1103                                 if (cp.raw) current_blob.raw = cp.raw;
1104                                 current_blob.owner_label = cp.owner_label;
1105                                 current_blob.owner_id = cp.owner_id;
1106                                 current_blob.call_number = cp.call_number;
1107                                 current_blob.owner_list = cp.owner_list;
1108                             }
1109                         }
1110                     });
1111
1112                     current_blob.barcode = current_blob.copy_count;
1113                     cp_list.push(current_blob);
1114                     new_list = cp_list;
1115
1116                     if (!vol) { // do the same for vol rows
1117
1118                         index = 0;
1119                         var cn_list = [];
1120                         prev_key = '';
1121                         current_blob = { copy_count : 0 };
1122                         angular.forEach(cp_list, function (cp) {
1123                             if (!prev_key) {
1124                                 prev_key = cp.owner_list.join('');
1125                                 current_blob.index = index++;
1126                                 current_blob.id_list = cp.id_list;
1127                                 if (cp.raw) current_blob.raw = cp.raw;
1128                                 current_blob.cn_count = 1;
1129                                 current_blob.copy_count = cp.copy_count;
1130                                 current_blob.owner_list = cp.owner_list;
1131                                 current_blob.owner_label = cp.owner_label;
1132                                 current_blob.owner_id = cp.owner_id;
1133                             } else {
1134                                 var current_key = cp.owner_list.join('');
1135                                 if (prev_key == current_key) { // collapse into current_blob
1136                                     current_blob.cn_count++;
1137                                     current_blob.copy_count += cp.copy_count;
1138                                     current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1139                                     if (cp.raw) current_blob.raw = current_blob.raw.concat(cp.raw);
1140                                 } else {
1141                                     current_blob.barcode = current_blob.copy_count;
1142                                     current_blob.call_number = { label : current_blob.cn_count };
1143                                     cn_list.push(current_blob);
1144                                     prev_key = current_key;
1145                                     current_blob = { copy_count : 0 };
1146                                     current_blob.index = index++;
1147                                     current_blob.id_list = cp.id_list;
1148                                     if (cp.raw) current_blob.raw = cp.raw;
1149                                     current_blob.owner_label = cp.owner_label;
1150                                     current_blob.owner_id = cp.owner_id;
1151                                     current_blob.cn_count = 1;
1152                                     current_blob.copy_count = cp.copy_count;
1153                                     current_blob.owner_list = cp.owner_list;
1154                                 }
1155                             }
1156                         });
1157     
1158                         current_blob.barcode = current_blob.copy_count;
1159                         current_blob.call_number = { label : current_blob.cn_count };
1160                         cn_list.push(current_blob);
1161                         new_list = cn_list;
1162     
1163                     }
1164                 }
1165
1166                 service.copies = new_list;
1167                 service.ongoing = false;
1168             },
1169
1170             null, // error
1171
1172             // notify reads the stream of copies, one at a time.
1173             function(cn) {
1174
1175                 var copies = cn.copies().filter(function(cp){ return cp.deleted() == 'f' });
1176                 cn.copies([]);
1177
1178                 angular.forEach(copies, function (cp) {
1179                     cp.call_number(cn);
1180                 });
1181
1182                 var owner_id = cn.owning_lib();
1183                 var owner = egCore.org.get(owner_id);
1184
1185                 var owner_name_list = [];
1186                 while (owner.parent_ou()) { // we're going to skip the top of the tree...
1187                     owner_name_list.unshift(owner.name());
1188                     owner = egCore.org.get(owner.parent_ou());
1189                 }
1190
1191                 if (copies[0]) {
1192                     var flat = [];
1193                     angular.forEach(copies, function (cp) {
1194                         var flat_cp = egCore.idl.toHash(cp);
1195                         flat_cp.owner_id = owner_id;
1196                         flat_cp.owner_list = owner_name_list;
1197                         flat_cp.id_list = [flat_cp.id];
1198                         flat_cp.raw = [cp];
1199                         flat.push(flat_cp);
1200                     });
1201
1202                     service.copies = service.copies.concat(flat);
1203                 } else if (empty) {
1204                     service.copies.push({
1205                         owner_id   : owner_id,
1206                         owner_list : owner_name_list,
1207                         call_number: egCore.idl.toHash(cn),
1208                         raw_call_number: cn
1209                     });
1210                 }
1211
1212                 return cn;
1213             }
1214         );
1215     }
1216
1217     return service;
1218 }])
1219
1220