]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/cat/catalog/app.js
webstaff: Refactor replace-barcode to be reusable, and reuse it in holdings maint
[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','egConfirmDialog',
230         'egGridDataProvider','egHoldGridActions','$timeout','$modal','holdingsSvc','egUser','conjoinedSvc',
231 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc,  egConfirmDialog,
232          egGridDataProvider , egHoldGridActions , $timeout , $modal , holdingsSvc , egUser , conjoinedSvc) {
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.add_to_record_bucket = function() {
254         var recId = $scope.record_id;
255         return $modal.open({
256             templateUrl: './cat/catalog/t_add_to_bucket',
257             animation: true,
258             size: 'md',
259             controller:
260                    ['$scope','$modalInstance',
261             function($scope , $modalInstance) {
262
263                 $scope.bucket_id = 0;
264                 $scope.newBucketName = '';
265                 $scope.allBuckets = [];
266                 egCore.net.request(
267                     'open-ils.actor',
268                     'open-ils.actor.container.retrieve_by_class.authoritative',
269                     egCore.auth.token(), egCore.auth.user().id(),
270                     'biblio', 'staff_client'
271                 ).then(function(buckets) { $scope.allBuckets = buckets; });
272
273                 $scope.add_to_bucket = function() {
274                     var item = new egCore.idl.cbrebi();
275                     item.bucket($scope.bucket_id);
276                     item.target_biblio_record_entry(recId);
277                     egCore.net.request(
278                         'open-ils.actor',
279                         'open-ils.actor.container.item.create',
280                         egCore.auth.token(), 'biblio', item
281                     ).then(function(resp) {
282                         $modalInstance.close();
283                     });
284                 }
285
286                 $scope.add_to_new_bucket = function() {
287                     var bucket = new egCore.idl.cbreb();
288                     bucket.owner(egCore.auth.user().id());
289                     bucket.name($scope.newBucketName);
290                     bucket.description('');
291                     bucket.btype('staff_client');
292
293                     egCore.net.request(
294                         'open-ils.actor',
295                         'open-ils.actor.container.create',
296                         egCore.auth.token(), 'biblio', bucket
297                     ).then(function(bucket) {
298                         $scope.bucket_id = bucket;
299                         $scope.add_to_bucket();
300                     });
301                 }
302
303                 $scope.cancel = function() {
304                     $modalInstance.dismiss();
305                 }
306             }]
307         });
308     }
309
310     $scope.stop_unload = false;
311     $scope.$watch('stop_unload',
312         function(newVal, oldVal) {
313             if (newVal && newVal != oldVal && $scope.opac_iframe) {
314                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
315                     return 'There is unsaved data in this record.'
316                 });
317             } else {
318                 if ($scope.opac_iframe)
319                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
320             }
321         }
322     );
323
324     // Set the "last bib" cookie, if we have that
325     if ($scope.record_id)
326         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
327
328     // also set it when the iframe changes to a new record
329     $scope.handle_page = function(url) {
330
331         if (!url || url == 'about:blank') {
332             // nothing loaded.  If we already have a record ID, leave it.
333             return;
334         }
335
336         var match = url.match(/\/+opac\/+record\/+(\d+)/);
337         if (match) {
338             $scope.record_id = match[1];
339             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
340             $scope.holdings_record_id_changed($scope.record_id);
341             conjoinedSvc.fetch($scope.record_id).then(function(){
342                 $scope.conjoinedGridDataProvider.refresh();
343             });
344             init_parts_url();
345         } else {
346             delete $scope.record_id;
347             $scope.from_route = false;
348         }
349
350         // child scope is executing this function, so our digest doesn't fire ... thus,
351         $scope.$apply();
352
353         if (!$scope.in_opac_call) {
354             if ($scope.record_id) {
355                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
356                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
357             } else {
358                 tab = $routeParams.record_tab || 'catalog';
359             }
360             $scope.set_record_tab(tab);
361         } else {
362             $scope.in_opac_call = false;
363         }
364     }
365
366     // xulG catalog handlers
367     $scope.handlers = { }
368
369     // ------------------------------------------------------------------
370     // Conjoined items
371
372     $scope.conjoinedGridControls = {};
373     $scope.conjoinedGridDataProvider = egGridDataProvider.instance({
374         get : function(offset, count) {
375             return this.arrayNotifier(conjoinedSvc.items, offset, count);
376         }
377     });
378
379     $scope.changeConjoinedType = function () {
380         var peers = egCore.idl.Clone($scope.conjoinedGridControls.selectedItems());
381         angular.forEach(peers, function (p) {
382             p.target_copy(p.target_copy().id());
383             p.peer_type(p.peer_type().id());
384         });
385
386         var conjoinedGridDataProviderRef = $scope.conjoinedGridDataProvider;
387
388         return $modal.open({
389             templateUrl: './cat/catalog/t_conjoined_selector',
390             animation: true,
391             controller:
392                    ['$scope','$modalInstance',
393             function($scope , $modalInstance) {
394                 $scope.update = true;
395
396                 $scope.peer_type = null;
397                 $scope.peer_type_list = [];
398                 conjoinedSvc.get_peer_types().then(function(list){
399                     $scope.peer_type_list = list;
400                 });
401     
402                 $scope.ok = function(type) {
403                     var promises = [];
404     
405                     angular.forEach(peers, function (p) {
406                         p.ischanged(1);
407                         p.peer_type(type);
408                         promises.push(egCore.pcrud.update(p));
409                     });
410     
411                     return $q.all(promises)
412                         .then(function(){$modalInstance.close()})
413                         .then(function(){return conjoinedSvc.fetch()})
414                         .then(function(){conjoinedGridDataProviderRef.refresh()});
415                 }
416     
417                 $scope.cancel = function($event) {
418                     $modalInstance.dismiss();
419                     $event.preventDefault();
420                 }
421             }]
422         });
423         
424     }
425
426     $scope.refreshConjoined = function () {
427         conjoinedSvc.fetch($scope.record_id)
428         .then(function(){$scope.conjoinedGridDataProvider.refresh();});
429     }
430
431     $scope.deleteSelectedConjoined = function () {
432         var peers = $scope.conjoinedGridControls.selectedItems();
433
434         if (peers.length > 0) {
435             egConfirmDialog.open(
436                 egCore.strings.CONFIRM_DELETE_PEERS,
437                 egCore.strings.CONFIRM_DELETE_PEERS_MESSAGE,
438                 {peers : peers.length}
439             ).result.then(function() {
440                 angular.forEach(peers, function (p) {
441                     p.isdeleted(1);
442                 });
443
444                 egCore.pcrud.remove(peers).then(function() {
445                     return conjoinedSvc.fetch();
446                 }).then(function() {
447                     $scope.conjoinedGridDataProvider.refresh();
448                 });
449             });
450         }
451     }
452     if ($scope.record_id)
453         conjoinedSvc.fetch($scope.record_id);
454
455     // ------------------------------------------------------------------
456     // Holdings
457
458     $scope.holdingsGridControls = {};
459     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
460         get : function(offset, count) {
461             return this.arrayNotifier(holdingsSvc.copies, offset, count);
462         }
463     });
464
465     $scope.requestItems = function() {
466         var copy_list = gatherSelectedHoldingsIds();
467         if (copy_list.length == 0) return;
468
469         return $modal.open({
470             templateUrl: './cat/catalog/t_request_items',
471             animation: true,
472             controller:
473                    ['$scope','$modalInstance',
474             function($scope , $modalInstance) {
475                 $scope.user = null;
476                 $scope.first_user_fetch = true;
477
478                 $scope.hold_data = {
479                     hold_type : 'C',
480                     copy_list : copy_list,
481                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
482                     user      : egCore.auth.user().id()
483                 };
484
485                 egUser.get( $scope.hold_data.user ).then(function(u) {
486                     $scope.user = u;
487                     $scope.barcode = u.card().barcode();
488                     $scope.user_name = egUser.format_name(u);
489                     $scope.hold_data.user = u.id();
490                 });
491
492                 $scope.user_name = '';
493                 $scope.barcode = '';
494                 $scope.$watch('barcode', function (n) {
495                     if (!$scope.first_user_fetch) {
496                         egUser.getByBarcode(n).then(function(u) {
497                             $scope.user = u;
498                             $scope.user_name = egUser.format_name(u);
499                             $scope.hold_data.user = u.id();
500                         }, function() {
501                             $scope.user = null;
502                             $scope.user_name = '';
503                             delete $scope.hold_data.user;
504                         });
505                     }
506                     $scope.first_user_fetch = false;
507                 });
508
509                 $scope.ok = function(h) {
510                     var args = {
511                         patronid  : h.user,
512                         hold_type : h.hold_type,
513                         pickup_lib: h.pickup_lib.id(),
514                         depth     : 0
515                     };
516
517                     egCore.net.request(
518                         'open-ils.circ',
519                         'open-ils.circ.holds.test_and_create.batch.override',
520                         egCore.auth.token(), args, h.copy_list
521                     );
522
523                     $modalInstance.close();
524                 }
525
526                 $scope.cancel = function($event) {
527                     $modalInstance.dismiss();
528                     $event.preventDefault();
529                 }
530             }]
531         });
532     }
533
534     $scope.replaceBarcodes = function() {
535         var copy_list = gatherSelectedRawCopies();
536         if (copy_list.length == 0) return;
537
538         var holdingsGridDataProviderRef = $scope.holdingsGridDataProvider;
539
540         angular.forEach(copy_list, function (cp) {
541             $modal.open({
542                 templateUrl: './cat/share/t_replace_barcode',
543                 animation: true,
544                 controller:
545                            ['$scope','$modalInstance',
546                     function($scope , $modalInstance) {
547                         $scope.isModal = true;
548                         $scope.focusBarcode = false;
549                         $scope.focusBarcode2 = true;
550                         $scope.barcode1 = cp.barcode();
551
552                         $scope.updateBarcode = function() {
553                             $scope.copyNotFound = false;
554                             $scope.updateOK = false;
555                 
556                             egCore.pcrud.search('acp',
557                                 {deleted : 'f', barcode : $scope.barcode1})
558                             .then(function(copy) {
559                 
560                                 if (!copy) {
561                                     $scope.focusBarcode = true;
562                                     $scope.copyNotFound = true;
563                                     return;
564                                 }
565                 
566                                 $scope.copyId = copy.id();
567                                 copy.barcode($scope.barcode2);
568                 
569                                 egCore.pcrud.update(copy).then(function(stat) {
570                                     $scope.updateOK = stat;
571                                     $scope.focusBarcode = true;
572                                     holdingsSvc.fetchAgain().then(function (){
573                                         holdingsGridDataProviderRef.refresh();
574                                     });
575                                 });
576
577                             });
578                             $modalInstance.close();
579                         }
580
581                         $scope.cancel = function($event) {
582                             $modalInstance.dismiss();
583                             $event.preventDefault();
584                         }
585                     }
586                 ]
587             });
588         });
589     }
590
591     // refresh the list of holdings when the record_id is changed.
592     $scope.holdings_record_id_changed = function(id) {
593         if ($scope.record_id != id) $scope.record_id = id;
594         console.log('record id changed to ' + id + ', loading new holdings');
595         holdingsSvc.fetch({
596             rid : $scope.record_id,
597             org : $scope.holdings_ou,
598             copy: $scope.holdings_show_copies,
599             vol : $scope.holdings_show_vols,
600             empty: $scope.holdings_show_empty
601         }).then(function() {
602             $scope.holdingsGridDataProvider.refresh();
603         });
604     }
605
606     // refresh the list of holdings when the filter lib is changed.
607     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
608     $scope.holdings_ou_changed = function(org) {
609         $scope.holdings_ou = org;
610         holdingsSvc.fetch({
611             rid : $scope.record_id,
612             org : $scope.holdings_ou,
613             copy: $scope.holdings_show_copies,
614             vol : $scope.holdings_show_vols,
615             empty: $scope.holdings_show_empty
616         }).then(function() {
617             $scope.holdingsGridDataProvider.refresh();
618         });
619     }
620
621     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
622         $scope[cb] = newVal;
623         egCore.hatch.setItem('cat.' + cb, newVal);
624         if (!norefresh) holdingsSvc.fetch({
625             rid : $scope.record_id,
626             org : $scope.holdings_ou,
627             copy: $scope.holdings_show_copies,
628             vol : $scope.holdings_show_vols,
629             empty: $scope.holdings_show_empty
630         }).then(function() {
631             $scope.holdingsGridDataProvider.refresh();
632         });
633     }
634
635     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
636         if (typeof x ==  'undefined') x = true;
637         $scope.holdings_cb_changed('holdings_show_vols',x,true);
638         $('#holdings_show_vols').prop('checked', x);
639     }).then(function(){
640         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
641             if (typeof x ==  'undefined') x = true;
642             $scope.holdings_cb_changed('holdings_show_copies',x,true);
643             $('#holdings_show_copies').prop('checked', x);
644         }).then(function(){
645             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
646                 if (typeof x ==  'undefined') x = true;
647                 $scope.holdings_cb_changed('holdings_show_empty',x);
648                 $('#holdings_show_empty').prop('checked', x);
649             })
650         })
651     });
652
653     $scope.vols_not_shown = function () {
654         return !$scope.holdings_show_vols;
655     }
656
657     $scope.copies_not_shown = function () {
658         return !$scope.holdings_show_copies;
659     }
660
661     $scope.holdings_checkbox_handler = function (item) {
662         $scope.holdings_cb_changed(item.checkbox,item.checked);
663     }
664
665     function gatherSelectedHoldingsIds () {
666         var cp_id_list = [];
667         angular.forEach(
668             $scope.holdingsGridControls.selectedItems(),
669             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
670         );
671         return cp_id_list;
672     }
673
674     function gatherSelectedRawCopies () {
675         var cp_list = [];
676         angular.forEach(
677             $scope.holdingsGridControls.selectedItems(),
678             function (item) { if (item.raw) cp_list = cp_list.concat(item.raw) }
679         );
680         return cp_list;
681     }
682
683     function gatherSelectedVolumeIds () {
684         var cn_id_list = [];
685         angular.forEach(
686             $scope.holdingsGridControls.selectedItems(),
687             function (item) {
688                 if (cn_id_list.indexOf(item.call_number.id) == -1)
689                     cn_id_list.push(item.call_number.id)
690             }
691         );
692         return cn_id_list;
693     }
694
695     $scope.selectedHoldingsDelete = function (vols, copies) {
696
697         var cnHash = {};
698         var perCnCopies = {};
699
700         var cn_count = 0;
701         var cp_count = 0;
702
703         angular.forEach(
704             $scope.holdingsGridControls.selectedItems(),
705             function (item) {
706                 if (vols && item.raw_call_number) {
707                     cnHash[item.call_number.id] = egCore.idl.Clone(item.raw_call_number);
708                     cnHash[item.call_number.id].isdeleted(1);
709                     cn_count++;
710                 } else if (copies) {
711                     angular.forEach(egCore.idl.Clone(item.raw), function (cp) {
712                         cp.isdeleted(1);
713                         cp_count++;
714                         var cn_id = cp.call_number().id();
715                         if (!cnHash[cn_id]) {
716                             cnHash[cn_id] = cp.call_number();
717                             perCnCopies[cn_id] = [cp];
718                         } else {
719                             perCnCopies[cn_id].push(cp);
720                         }
721                         cp.call_number(cn_id); // prevent loops in JSON-ification
722                     });
723
724                 }
725             }
726         );
727
728         angular.forEach(perCnCopies, function (v, k) {
729             if (vols) {
730                 cnHash[k].isdeleted(1);
731                 cn_count++;
732             }
733             cnHash[k].copies(v);
734         });
735
736         cnList = [];
737         angular.forEach(cnHash, function (v, k) {
738             cnList.push(v);
739         });
740
741         if (cnList.length == 0) return;
742
743         egConfirmDialog.open(
744             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
745             egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
746             {copies : cp_count, volumes : cn_count}
747         ).result.then(function() {
748             egCore.net.request(
749                 'open-ils.cat',
750                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
751                 egCore.auth.token(), cnList, 1, {}
752             ).then(function(update_count) {
753                 $scope.holdingsGridDataProvider.refresh();
754             });
755         });
756     }
757     $scope.selectedHoldingsCopyDelete = function () { $scope.selectedHoldingsDelete(false,true) }
758     $scope.selectedHoldingsVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,true) }
759     $scope.selectedHoldingsEmptyVolCopyDelete = function () { $scope.selectedHoldingsDelete(true,false) }
760
761     spawnHoldingsAdd = function (vols,copies){
762         var raw = [];
763         if (copies) { // just a copy on existing volumes
764             angular.forEach(gatherSelectedVolumeIds(), function (v) {
765                 raw.push( {callnumber : v} );
766             });
767         } else if (vols) {
768             angular.forEach(
769                 $scope.holdingsGridControls.selectedItems(),
770                 function (item) {
771                     raw.push({owner : item.owner_id});
772                 }
773             );
774         }
775
776         egCore.net.request(
777             'open-ils.actor',
778             'open-ils.actor.anon_cache.set_value',
779             null, 'edit-these-copies', {
780                 record_id: $scope.record_id,
781                 raw: raw,
782                 hide_vols : false,
783                 hide_copies : false
784             }
785         ).then(function(key) {
786             if (key) {
787                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
788                 $timeout(function() { $window.open(url, '_blank') });
789             } else {
790                 alert('Could not create anonymous cache key!');
791             }
792         });
793     }
794     $scope.selectedHoldingsVolCopyAdd = function () { spawnHoldingsAdd(true,false) }
795     $scope.selectedHoldingsCopyAdd = function () { spawnHoldingsAdd(false,true) }
796
797     spawnHoldingsEdit = function (hide_vols,hide_copies){
798         egCore.net.request(
799             'open-ils.actor',
800             'open-ils.actor.anon_cache.set_value',
801             null, 'edit-these-copies', {
802                 record_id: $scope.record_id,
803                 copies: gatherSelectedHoldingsIds(),
804                 hide_vols : hide_vols,
805                 hide_copies : hide_copies
806             }
807         ).then(function(key) {
808             if (key) {
809                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
810                 $timeout(function() { $window.open(url, '_blank') });
811             } else {
812                 alert('Could not create anonymous cache key!');
813             }
814         });
815     }
816     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
817     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
818     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
819
820     $scope.selectedHoldingsItemStatus = function (){
821         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
822         $timeout(function() { $window.open(url, '_blank') });
823     }
824
825     $scope.markVolAsItemTarget = function() {
826         if ($scope.holdingsGridControls.selectedItems()[0].call_number.id) { // cn.id missing when vols are collapsed
827             egCore.hatch.setLocalItem(
828                 'eg.cat.item_transfer_target',
829                 $scope.holdingsGridControls.selectedItems()[0].call_number.id
830             );
831         }
832     }
833
834     $scope.markLibAsVolTarget = function() {
835         egCore.hatch.setLocalItem(
836             'eg.cat.volume_transfer_target',
837             $scope.holdingsGridControls.selectedItems()[0].owner_id
838         );
839     }
840
841     $scope.selectedHoldingsItemStatusDetail = function (){
842         angular.forEach(
843             gatherSelectedHoldingsIds(),
844             function (cid) {
845                 var url = egCore.env.basePath +
846                           'cat/item/' + cid;
847                 $timeout(function() { $window.open(url, '_blank') });
848             }
849         );
850     }
851
852     $scope.transferVolumes = function (){
853         var xfer_target = egCore.hatch.getLocalItem('eg.cat.volume_transfer_target');
854
855         if (xfer_target) {
856             egCore.net.request(
857                 'open-ils.cat',
858                 'open-ils.open-ils.cat.asset.volume.batch.transfer.override',
859                 egCore.auth.token(), {
860                     docid   : $scope.record_id,
861                     lib     : xfer_target,
862                     volumes : gatherSelectedVolumeIds()
863                 }
864             ).then(function(success) {
865                 if (success) {
866                     holdingsSvc.fetchAgain().then(function() {
867                         $scope.holdingsGridDataProvider.refresh();
868                     });
869                 } else {
870                     alert('Could not transfer volumes!');
871                 }
872             });
873         }
874         
875     }
876
877     $scope.transferItems = function (){
878         var xfer_target = egCore.hatch.getLocalItem('eg.cat.item_transfer_target');
879         if (xfer_target) {
880             var copy_list = gatherSelectedRawCopies();
881
882             angular.forEach(copy_list, function (cp) {
883                 cp.call_number(xfer_target);
884             });
885
886             egCore.pcrud.update(
887                 copy_list
888             ).then(function(success) {
889                 if (success) {
890                     holdingsSvc.fetchAgain().then(function() {
891                         $scope.holdingsGridDataProvider.refresh();
892                     });
893                 } else {
894                     alert('Could not transfer items!');
895                 }
896             });
897         }
898         
899     }
900
901     $scope.selectedHoldingsItemStatusTgrEvt = function (){
902         angular.forEach(
903             gatherSelectedHoldingsIds(),
904             function (cid) {
905                 var url = egCore.env.basePath +
906                           'cat/item/' + cid + '/triggered_events';
907                 $timeout(function() { $window.open(url, '_blank') });
908             }
909         );
910     }
911
912     $scope.selectedHoldingsItemStatusHolds = function (){
913         angular.forEach(
914             gatherSelectedHoldingsIds(),
915             function (cid) {
916                 var url = egCore.env.basePath +
917                           'cat/item/' + cid + '/holds';
918                 $timeout(function() { $window.open(url, '_blank') });
919             }
920         );
921     }
922
923     $scope.selectedHoldingsDamaged = function () {
924         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
925             holdingsSvc.fetchAgain().then(function() {
926                 $scope.holdingsGridDataProvider.refresh();
927             });
928         });
929     }
930
931     $scope.selectedHoldingsMissing = function () {
932         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
933             holdingsSvc.fetchAgain().then(function() {
934                 $scope.holdingsGridDataProvider.refresh();
935             });
936         });
937     }
938
939     $scope.attach_to_peer_bib = function() {
940         var copy_list = gatherSelectedHoldingsIds();
941         if (copy_list.length == 0) return;
942
943         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
944             if (!target_record) return;
945
946             return $modal.open({
947                 templateUrl: './cat/catalog/t_conjoined_selector',
948                 animation: true,
949                 controller:
950                        ['$scope','$modalInstance',
951                 function($scope , $modalInstance) {
952                     $scope.update = false;
953
954                     $scope.peer_type = null;
955                     $scope.peer_type_list = [];
956                     conjoinedSvc.get_peer_types().then(function(list){
957                         $scope.peer_type_list = list;
958                     });
959     
960                     $scope.ok = function(type) {
961                         var promises = [];
962     
963                         angular.forEach(copy_list, function (cp) {
964                             var n = new egCore.idl.bpbcm();
965                             n.isnew(true);
966                             n.peer_record(target_record);
967                             n.target_copy(cp);
968                             n.peer_type(type);
969                             promises.push(egCore.pcrud.create(n));
970                         });
971     
972                         return $q.all(promises).then(function(){$modalInstance.close()});
973                     }
974     
975                     $scope.cancel = function($event) {
976                         $modalInstance.dismiss();
977                         $event.preventDefault();
978                     }
979                 }]
980             });
981         });
982     }
983
984
985     // ------------------------------------------------------------------
986     // Holds 
987     var provider = egGridDataProvider.instance({});
988     $scope.hold_grid_data_provider = provider;
989     $scope.grid_actions = egHoldGridActions;
990     $scope.grid_actions.refresh = function () { provider.refresh() };
991     $scope.hold_grid_controls = {};
992
993     var hold_ids = []; // current list of holds
994     function fetchHolds(offset, count) {
995         var ids = hold_ids.slice(offset, offset + count);
996         return egHolds.fetch_holds(ids).then(null, null,
997             function(hold_data) { 
998                 return hold_data;
999             }
1000         );
1001     }
1002
1003     provider.get = function(offset, count) {
1004         if ($scope.record_tab != 'holds') return $q.when();
1005         var deferred = $q.defer();
1006         hold_ids = []; // no caching ATM
1007
1008         // fetch the IDs
1009         egCore.net.request(
1010             'open-ils.circ',
1011             'open-ils.circ.holds.retrieve_all_from_title',
1012             egCore.auth.token(), $scope.record_id, 
1013             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
1014         ).then(
1015             function(hold_data) {
1016                 angular.forEach(hold_data, function(list, type) {
1017                     hold_ids = hold_ids.concat(list);
1018                 });
1019                 fetchHolds(offset, count).then(
1020                     deferred.resolve, null, deferred.notify);
1021             }
1022         );
1023
1024         return deferred.promise;
1025     }
1026
1027     $scope.detail_view = function(action, user_data, items) {
1028         if (h = items[0]) {
1029             $scope.detail_hold_id = h.hold.id();
1030         }
1031     }
1032
1033     $scope.list_view = function(items) {
1034          $scope.detail_hold_id = null;
1035     }
1036
1037     // refresh the list of record holds when the pickup lib is changed.
1038     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
1039     $scope.pickup_ou_changed = function(org) {
1040         $scope.pickup_ou = org;
1041         provider.refresh();
1042     }
1043
1044     $scope.print_holds = function() {
1045         var holds = [];
1046         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
1047             holds.push({
1048                 hold : egCore.idl.toHash(item.hold),
1049                 patron_last : item.patron_last,
1050                 patron_alias : item.patron_alias,
1051                 patron_barcode : item.patron_barcode,
1052                 copy : egCore.idl.toHash(item.copy),
1053                 volume : egCore.idl.toHash(item.volume),
1054                 title : item.mvr.title(),
1055                 author : item.mvr.author()
1056             });
1057         });
1058
1059         egCore.print.print({
1060             context : 'receipt', 
1061             template : 'holds_for_bib', 
1062             scope : {holds : holds}
1063         });
1064     }
1065
1066     $scope.mark_hold_transfer_dest = function() {
1067         egCore.hatch.setLocalItem(
1068             'eg.circ.hold.title_transfer_target', $scope.record_id);
1069     }
1070
1071     // UI presents this option as "all holds"
1072     $scope.transfer_holds_to_marked = function() {
1073         var hold_ids = $scope.hold_grid_controls.allItems().map(
1074             function(hold_data) {return hold_data.hold.id()});
1075         egHolds.transfer_to_marked_title(hold_ids);
1076     }
1077
1078     // ------------------------------------------------------------------
1079     // Initialize the selected tab
1080
1081     function init_cat_url() {
1082         // Set the initial catalog URL.  This only happens once.
1083         // The URL is otherwise generated through user navigation.
1084         if ($scope.catalog_url) return; 
1085
1086         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
1087
1088         // A record ID in the path indicates a request for the record-
1089         // specific page.
1090         if ($routeParams.record_id) {
1091             url = url.replace(/advanced/, '/record/' + $scope.record_id);
1092         }
1093
1094         $scope.catalog_url = url;
1095     }
1096
1097     function init_parts_url() {
1098         $scope.parts_url = $location
1099             .absUrl()
1100             .replace(
1101                 /\/staff.*/,
1102                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
1103             );
1104     }
1105
1106     $scope.set_record_tab = function(tab) {
1107         $scope.record_tab = tab;
1108
1109         switch(tab) {
1110
1111             case 'monoparts':
1112                 init_parts_url();
1113                 break;
1114
1115             case 'catalog':
1116                 init_cat_url();
1117                 break;
1118
1119             case 'holds':
1120                 $scope.detail_hold_record_id = $scope.record_id; 
1121                 // refresh the holds grid
1122                 provider.refresh();
1123                 break;
1124         }
1125     }
1126
1127     $scope.set_default_record_tab = function() {
1128         egCore.hatch.setLocalItem(
1129             'eg.cat.default_record_tab', $scope.record_tab);
1130         $timeout(function(){$scope.default_tab = $scope.record_tab});
1131     }
1132
1133     var tab;
1134     if ($scope.record_id) {
1135         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
1136         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
1137
1138     } else {
1139         tab = $routeParams.record_tab || 'catalog';
1140     }
1141     $scope.set_record_tab(tab);
1142
1143 }])
1144
1145 .controller('AuthorityCtrl',
1146        ['$scope','$routeParams','$location','$window','$q','egCore',
1147 function($scope , $routeParams , $location , $window , $q , egCore) {
1148
1149     // set record ID on page load if available...
1150     $scope.authority_id = $routeParams.authority_id;
1151
1152     if ($routeParams.authority_id) $scope.from_route = true;
1153     else $scope.from_route = false;
1154
1155     $scope.stop_unload = false;
1156 }])
1157
1158 .controller('URLVerifyCtrl',
1159        ['$scope','$location',
1160 function($scope , $location) {
1161     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
1162 }])
1163
1164 .controller('VandelayCtrl',
1165        ['$scope','$location',
1166 function($scope , $location) {
1167     $scope.vandelay_url = $location.absUrl().replace(/\/staff.*/, '/vandelay/vandelay');
1168 }])
1169
1170 .controller('ManageAuthoritiesCtrl',
1171        ['$scope','$location',
1172 function($scope , $location) {
1173     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
1174 }])
1175
1176 .controller('BatchEditCtrl',
1177        ['$scope','$location','$routeParams',
1178 function($scope , $location , $routeParams) {
1179     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
1180     if ($routeParams.container_type) {
1181         switch ($routeParams.container_type) {
1182             case 'bucket':
1183                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
1184                 break;
1185             case 'record':
1186                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
1187                 break;
1188         };
1189     }
1190 }])
1191
1192  
1193 .filter('boolText', function(){
1194     return function (v) {
1195         return v == 't';
1196     }
1197 })
1198
1199 .factory('holdingsSvc', 
1200        ['egCore','$q',
1201 function(egCore , $q) {
1202
1203     var service = {
1204         ongoing : false,
1205         copies : [], // record search results
1206         index : 0, // search grid index
1207         org : null,
1208         rid : null
1209     };
1210
1211     service.flesh = {   
1212         flesh : 2, 
1213         flesh_fields : {
1214             acp : ['status','location'],
1215             acn : ['prefix','suffix','copies']
1216         }
1217     }
1218
1219     service.fetchAgain = function() {
1220         return service.fetch({
1221             rid: service.rid,
1222             org: service.org,
1223             copy: service.copy,
1224             vol: service.vol,
1225             empty: service.empty
1226         })
1227     }
1228
1229     // resolved with the last received copy
1230     service.fetch = function(opts) {
1231         if (service.ongoing) {
1232             console.log('Skipping fetch, ongoing = true');
1233             return $q.when();
1234         }
1235
1236         var rid = opts.rid;
1237         var org = opts.org;
1238         var copy = opts.copy;
1239         var vol = opts.vol;
1240         var empty = opts.empty;
1241
1242         if (!rid) return $q.when();
1243         if (!org) return $q.when();
1244
1245         service.ongoing = true;
1246
1247         service.rid = rid;
1248         service.org = org;
1249         service.copy = opts.copy;
1250         service.vol = opts.vol;
1251         service.empty = opts.empty;
1252
1253         service.copies = [];
1254         service.index = 0;
1255
1256         var org_list = egCore.org.descendants(org.id(), true);
1257         console.log('Holdings fetch with: rid='+rid+' org='+org_list+' copy='+copy+' vol='+vol+' empty='+empty);
1258
1259         return egCore.pcrud.search(
1260             'acn',
1261             {record : rid, owning_lib : org_list, deleted : 'f'},
1262             service.flesh
1263         ).then(
1264             function() { // finished
1265                 service.copies = service.copies.sort(
1266                     function (a, b) {
1267                         function compare_array (x, y, i) {
1268                             if (x[i] && y[i]) { // both have values
1269                                 if (x[i] == y[i]) { // need to look deeper
1270                                     return compare_array(x, y, ++i);
1271                                 }
1272
1273                                 if (x[i] < y[i]) { // x is first
1274                                     return -1;
1275                                 } else if (x[i] > y[i]) { // y is first
1276                                     return 1;
1277                                 }
1278
1279                             } else { // no orgs to compare ...
1280                                 if (x[i]) return -1;
1281                                 if (y[i]) return 1;
1282                             }
1283                             return 0;
1284                         }
1285
1286                         var owner_order = compare_array(a.owner_list, b.owner_list, 0);
1287                         if (!owner_order) {
1288                             // now compare on CN label
1289                             if (a.call_number.label < b.call_number.label) return -1;
1290                             if (a.call_number.label > b.call_number.label) return 1;
1291
1292                             // try copy number
1293                             if (a.copy_number < b.copy_number) return -1;
1294                             if (a.copy_number > b.copy_number) return 1;
1295
1296                             // finally, barcode
1297                             if (a.barcode < b.barcode) return -1;
1298                             if (a.barcode > b.barcode) return 1;
1299                         }
1300                         return owner_order;
1301                     }
1302                 );
1303
1304                 // create a label using just the unique part of the owner list
1305                 var index = 0;
1306                 var prev_owner_list;
1307                 angular.forEach(service.copies, function (cp) {
1308                     if (!prev_owner_list) {
1309                         cp.owner_label = cp.owner_list.join(' ... ');
1310                     } else {
1311                         var current_owner_list = cp.owner_list.slice();
1312                         while (current_owner_list[1] && prev_owner_list[1] && current_owner_list[0] == prev_owner_list[0]) {
1313                             current_owner_list.shift();
1314                             prev_owner_list.shift();
1315                         }
1316                         cp.owner_label = current_owner_list.join(' ... ');
1317                     }
1318
1319                     cp.index = index++;
1320                     prev_owner_list = cp.owner_list.slice();
1321                 });
1322
1323                 var new_list = service.copies;
1324                 if (!copy || !vol) { // collapse copy rows, supply a count instead
1325
1326                     index = 0;
1327                     var cp_list = [];
1328                     var prev_key;
1329                     var current_blob = { copy_count : 0 };
1330                     angular.forEach(new_list, function (cp) {
1331                         if (!prev_key) {
1332                             prev_key = cp.owner_list.join('') + cp.call_number.label;
1333                             if (cp.barcode) current_blob.copy_count = 1;
1334                             current_blob.index = index++;
1335                             current_blob.id_list = cp.id_list;
1336                             if (cp.raw) current_blob.raw = cp.raw;
1337                             current_blob.call_number = cp.call_number;
1338                             current_blob.owner_list = cp.owner_list;
1339                             current_blob.owner_label = cp.owner_label;
1340                             current_blob.owner_id = cp.owner_id;
1341                         } else {
1342                             var current_key = cp.owner_list.join('') + cp.call_number.label;
1343                             if (prev_key == current_key) { // collapse into current_blob
1344                                 current_blob.copy_count++;
1345                                 current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1346                                 current_blob.raw = current_blob.raw.concat(cp.raw);
1347                             } else {
1348                                 current_blob.barcode = current_blob.copy_count;
1349                                 cp_list.push(current_blob);
1350                                 prev_key = current_key;
1351                                 current_blob = { copy_count : 0 };
1352                                 if (cp.barcode) current_blob.copy_count = 1;
1353                                 current_blob.index = index++;
1354                                 current_blob.id_list = cp.id_list;
1355                                 if (cp.raw) current_blob.raw = cp.raw;
1356                                 current_blob.owner_label = cp.owner_label;
1357                                 current_blob.owner_id = cp.owner_id;
1358                                 current_blob.call_number = cp.call_number;
1359                                 current_blob.owner_list = cp.owner_list;
1360                             }
1361                         }
1362                     });
1363
1364                     current_blob.barcode = current_blob.copy_count;
1365                     cp_list.push(current_blob);
1366                     new_list = cp_list;
1367
1368                     if (!vol) { // do the same for vol rows
1369
1370                         index = 0;
1371                         var cn_list = [];
1372                         prev_key = '';
1373                         current_blob = { copy_count : 0 };
1374                         angular.forEach(cp_list, function (cp) {
1375                             if (!prev_key) {
1376                                 prev_key = cp.owner_list.join('');
1377                                 current_blob.index = index++;
1378                                 current_blob.id_list = cp.id_list;
1379                                 if (cp.raw) current_blob.raw = cp.raw;
1380                                 current_blob.cn_count = 1;
1381                                 current_blob.copy_count = cp.copy_count;
1382                                 current_blob.owner_list = cp.owner_list;
1383                                 current_blob.owner_label = cp.owner_label;
1384                                 current_blob.owner_id = cp.owner_id;
1385                             } else {
1386                                 var current_key = cp.owner_list.join('');
1387                                 if (prev_key == current_key) { // collapse into current_blob
1388                                     current_blob.cn_count++;
1389                                     current_blob.copy_count += cp.copy_count;
1390                                     current_blob.id_list = current_blob.id_list.concat(cp.id_list);
1391                                     if (cp.raw) current_blob.raw = current_blob.raw.concat(cp.raw);
1392                                 } else {
1393                                     current_blob.barcode = current_blob.copy_count;
1394                                     current_blob.call_number = { label : current_blob.cn_count };
1395                                     cn_list.push(current_blob);
1396                                     prev_key = current_key;
1397                                     current_blob = { copy_count : 0 };
1398                                     current_blob.index = index++;
1399                                     current_blob.id_list = cp.id_list;
1400                                     if (cp.raw) current_blob.raw = cp.raw;
1401                                     current_blob.owner_label = cp.owner_label;
1402                                     current_blob.owner_id = cp.owner_id;
1403                                     current_blob.cn_count = 1;
1404                                     current_blob.copy_count = cp.copy_count;
1405                                     current_blob.owner_list = cp.owner_list;
1406                                 }
1407                             }
1408                         });
1409     
1410                         current_blob.barcode = current_blob.copy_count;
1411                         current_blob.call_number = { label : current_blob.cn_count };
1412                         cn_list.push(current_blob);
1413                         new_list = cn_list;
1414     
1415                     }
1416                 }
1417
1418                 service.copies = new_list;
1419                 service.ongoing = false;
1420             },
1421
1422             null, // error
1423
1424             // notify reads the stream of copies, one at a time.
1425             function(cn) {
1426
1427                 var copies = cn.copies().filter(function(cp){ return cp.deleted() == 'f' });
1428                 cn.copies([]);
1429
1430                 angular.forEach(copies, function (cp) {
1431                     cp.call_number(cn);
1432                 });
1433
1434                 var owner_id = cn.owning_lib();
1435                 var owner = egCore.org.get(owner_id);
1436
1437                 var owner_name_list = [];
1438                 while (owner.parent_ou()) { // we're going to skip the top of the tree...
1439                     owner_name_list.unshift(owner.name());
1440                     owner = egCore.org.get(owner.parent_ou());
1441                 }
1442
1443                 if (copies[0]) {
1444                     var flat = [];
1445                     angular.forEach(copies, function (cp) {
1446                         var flat_cp = egCore.idl.toHash(cp);
1447                         flat_cp.owner_id = owner_id;
1448                         flat_cp.owner_list = owner_name_list;
1449                         flat_cp.id_list = [flat_cp.id];
1450                         flat_cp.raw = [cp];
1451                         flat.push(flat_cp);
1452                     });
1453
1454                     service.copies = service.copies.concat(flat);
1455                 } else if (empty) {
1456                     service.copies.push({
1457                         owner_id   : owner_id,
1458                         owner_list : owner_name_list,
1459                         call_number: egCore.idl.toHash(cn),
1460                         raw_call_number: cn
1461                     });
1462                 }
1463
1464                 return cn;
1465             }
1466         );
1467     }
1468
1469     return service;
1470 }])
1471
1472 .factory('conjoinedSvc', 
1473        ['egCore','$q',
1474 function(egCore , $q) {
1475
1476     var service = {
1477         items : [], // record search results
1478         index : 0, // search grid index
1479         rid : null
1480     };
1481
1482     service.flesh = {   
1483         flesh : 4, 
1484         flesh_fields : {
1485             bpbcm : ['target_copy','peer_type'],
1486             acp : ['call_number'],
1487             acn : ['record'],
1488             bre : ['simple_record']
1489         },
1490         // avoid fetching the MARC blob by specifying which
1491         // fields on the bre to select.  More may be needed.
1492         // note that fleshed fields are explicitly selected.
1493         select : { bre : ['id'] },
1494         order_by : { bpbcm : ['id'] },
1495     }
1496
1497     // resolved with the last received copy
1498     service.fetch = function(rid) {
1499         if (!rid && !service.rid) return $q.when();
1500
1501         if (rid) service.rid = rid;
1502         service.items = [];
1503         service.index = 0;
1504
1505         return egCore.pcrud.search(
1506             'bpbcm',
1507             {peer_record : service.rid},
1508             service.flesh,
1509             {atomic : true}
1510         ).then( function(list) { // finished
1511             service.items = list;
1512             return service.items;
1513         });
1514     }
1515
1516     // returns a promise resolved with the list of peer bib types
1517     service.get_peer_types = function() {
1518         if (egCore.env.bpt)
1519             return $q.when(egCore.env.bpt.list);
1520
1521         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
1522         .then(function(list) {
1523             egCore.env.absorbList(list, 'bpt');
1524             return list;
1525         });
1526     };
1527
1528     return service;
1529 }])
1530
1531