358e97efc93b673d8a6c172911d47b519efa4925
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / catalog / app.js
1 /**
2  * TPAC Frame App
3  *
4  * currently, this app doesn't use routes for each sub-ui, because 
5  * reloading the catalog each time is sloooow.  better so far to 
6  * swap out divs w/ ng-if / ng-show / ng-hide as needed.
7  *
8  */
9
10 angular.module('egCatalogApp', ['ui.bootstrap','ngRoute','egCoreMod','egGridMod', 'egMarcMod'])
11
12 .config(function($routeProvider, $locationProvider, $compileProvider) {
13     $locationProvider.html5Mode(true);
14     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
15
16     var resolver = {delay : 
17         ['egStartup', function(egStartup) {return egStartup.go()}]}
18
19     $routeProvider.when('/cat/catalog/index', {
20         templateUrl: './cat/catalog/t_catalog',
21         controller: 'CatalogCtrl',
22         resolve : resolver
23     });
24
25     $routeProvider.when('/cat/catalog/retrieve_by_id', {
26         templateUrl: './cat/catalog/t_retrieve_by_id',
27         controller: 'CatalogRecordRetrieve',
28         resolve : resolver
29     });
30
31     $routeProvider.when('/cat/catalog/retrieve_by_tcn', {
32         templateUrl: './cat/catalog/t_retrieve_by_tcn',
33         controller: 'CatalogRecordRetrieve',
34         resolve : resolver
35     });
36
37     // create some catalog page-specific mappings
38     $routeProvider.when('/cat/catalog/record/:record_id', {
39         templateUrl: './cat/catalog/t_catalog',
40         controller: 'CatalogCtrl',
41         resolve : resolver
42     });
43
44     // create some catalog page-specific mappings
45     $routeProvider.when('/cat/catalog/record/:record_id/:record_tab', {
46         templateUrl: './cat/catalog/t_catalog',
47         controller: 'CatalogCtrl',
48         resolve : resolver
49     });
50
51     $routeProvider.when('/cat/catalog/batchEdit', {
52         templateUrl: './cat/catalog/t_batchedit',
53         controller: 'BatchEditCtrl',
54         resolve : resolver
55     });
56
57     $routeProvider.when('/cat/catalog/batchEdit/:container_type/:container_id', {
58         templateUrl: './cat/catalog/t_batchedit',
59         controller: 'BatchEditCtrl',
60         resolve : resolver
61     });
62
63     $routeProvider.when('/cat/catalog/vandelay', {
64         templateUrl: './cat/catalog/t_vandelay',
65         controller: 'VandelayCtrl',
66         resolve : resolver
67     });
68
69     $routeProvider.when('/cat/catalog/verifyURLs', {
70         templateUrl: './cat/catalog/t_verifyurls',
71         controller: 'URLVerifyCtrl',
72         resolve : resolver
73     });
74
75     $routeProvider.when('/cat/catalog/manageAuthorities', {
76         templateUrl: './cat/catalog/t_manageauthorities',
77         controller: 'ManageAuthoritiesCtrl',
78         resolve : resolver
79     });
80
81     $routeProvider.otherwise({redirectTo : '/cat/catalog/index'});
82 })
83
84
85 /**
86  * */
87 .controller('CatalogRecordRetrieve',
88        ['$scope','$routeParams','$location','$q','egCore',
89 function($scope , $routeParams , $location , $q , egCore ) {
90
91     $scope.focusMe = true;
92
93     // jump to the patron checkout UI
94     function loadRecord(record_id) {
95         $location
96         .path('/cat/catalog/record/' + record_id);
97     }
98
99     $scope.submitId = function(args) {
100         $scope.recordNotFound = null;
101         if (!args.record_id) return;
102
103         // blur so next time it's set to true it will re-apply select()
104         $scope.selectMe = false;
105
106         return loadRecord(args.record_id);
107     }
108
109     $scope.submitTCN = function(args) {
110         $scope.recordNotFound = null;
111         $scope.moreRecordsFound = null;
112         if (!args.record_tcn) return;
113
114         // blur so next time it's set to true it will re-apply select()
115         $scope.selectMe = false;
116
117         // lookup TCN
118         egCore.net.request(
119             'open-ils.search',
120             'open-ils.search.biblio.tcn',
121             args.record_tcn)
122
123         .then(function(resp) { // get_barcodes
124
125             if (evt = egCore.evt.parse(resp)) {
126                 alert(evt); // FIXME
127                 return;
128             }
129
130             if (!resp.count) {
131                 $scope.recordNotFound = args.record_tcn;
132                 $scope.selectMe = true;
133                 return;
134             }
135
136             if (resp.count > 1) {
137                 $scope.moreRecordsFound = args.record_tcn;
138                 $scope.selectMe = true;
139                 return;
140             }
141
142             var record_id = resp.ids[0];
143             return loadRecord(record_id);
144         });
145     }
146
147 }])
148
149 .controller('CatalogCtrl',
150        ['$scope','$routeParams','$location','$window','$q','egCore','egHolds','egCirc',
151         'egGridDataProvider','egHoldGridActions','$timeout','holdingsSvc',
152 function($scope , $routeParams , $location , $window , $q , egCore , egHolds , egCirc, 
153          egGridDataProvider , egHoldGridActions , $timeout , holdingsSvc) {
154
155     // set record ID on page load if available...
156     $scope.record_id = $routeParams.record_id;
157
158     if ($routeParams.record_id) $scope.from_route = true;
159     else $scope.from_route = false;
160
161     // will hold a ref to the opac iframe
162     $scope.opac_iframe = null;
163     $scope.parts_iframe = null;
164
165     $scope.in_opac_call = false;
166     $scope.opac_call = function (opac_frame_function, force_opac_tab) {
167         if ($scope.opac_iframe) {
168             if (force_opac_tab) $scope.record_tab = 'catalog';
169             $scope.in_opac_call = true;
170             $scope.opac_iframe.dom.contentWindow[opac_frame_function]();
171         }
172     }
173
174     $scope.stop_unload = false;
175     $scope.$watch('stop_unload',
176         function(newVal, oldVal) {
177             if (newVal && newVal != oldVal && $scope.opac_iframe) {
178                 $($scope.opac_iframe.dom.contentWindow).on('beforeunload', function(){
179                     return 'There is unsaved data in this record.'
180                 });
181             } else {
182                 if ($scope.opac_iframe)
183                     $($scope.opac_iframe.dom.contentWindow).off('beforeunload');
184             }
185         }
186     );
187
188     // Set the "last bib" cookie, if we have that
189     if ($scope.record_id)
190         egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
191
192     // also set it when the iframe changes to a new record
193     $scope.handle_page = function(url) {
194
195         if (!url || url == 'about:blank') {
196             // nothing loaded.  If we already have a record ID, leave it.
197             return;
198         }
199
200         var match = url.match(/\/+opac\/+record\/+(\d+)/);
201         if (match) {
202             $scope.record_id = match[1];
203             egCore.hatch.setLocalItem("eg.cat.last_record_retrieved", $scope.record_id);
204             $scope.holdings_record_id_changed($scope.record_id);
205             init_parts_url();
206         } else {
207             delete $scope.record_id;
208             $scope.from_route = false;
209         }
210
211         // child scope is executing this function, so our digest doesn't fire ... thus,
212         $scope.$apply();
213
214         if (!$scope.in_opac_call) {
215             if ($scope.record_id) {
216                 $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
217                 tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
218             } else {
219                 tab = $routeParams.record_tab || 'catalog';
220             }
221             $scope.set_record_tab(tab);
222         } else {
223             $scope.in_opac_call = false;
224         }
225     }
226
227     // xulG catalog handlers
228     $scope.handlers = { }
229
230     // ------------------------------------------------------------------
231     // Holdings
232
233     $scope.holdingsGridControls = {};
234     $scope.holdingsGridDataProvider = egGridDataProvider.instance({
235         get : function(offset, count) {
236             return this.arrayNotifier(holdingsSvc.copies, offset, count);
237         }
238     });
239
240     // refresh the list of holdings when the record_id is changed.
241     $scope.holdings_record_id_changed = function(id) {
242         if ($scope.record_id != id) $scope.record_id = id;
243         console.log('record id changed to ' + id + ', loading new holdings');
244         holdingsSvc.fetch({
245             rid : $scope.record_id,
246             org : $scope.holdings_ou,
247             copy: $scope.holdings_show_copies,
248             vol : $scope.holdings_show_vols,
249             empty: $scope.holdings_show_empty
250         }).then(function() {
251             $scope.holdingsGridDataProvider.refresh();
252         });
253     }
254
255     // refresh the list of holdings when the filter lib is changed.
256     $scope.holdings_ou = egCore.org.get(egCore.auth.user().ws_ou());
257     $scope.holdings_ou_changed = function(org) {
258         $scope.holdings_ou = org;
259         holdingsSvc.fetch({
260             rid : $scope.record_id,
261             org : $scope.holdings_ou,
262             copy: $scope.holdings_show_copies,
263             vol : $scope.holdings_show_vols,
264             empty: $scope.holdings_show_empty
265         }).then(function() {
266             $scope.holdingsGridDataProvider.refresh();
267         });
268     }
269
270     $scope.holdings_cb_changed = function(cb,newVal,norefresh) {
271         $scope[cb] = newVal;
272         egCore.hatch.setItem('cat.' + cb, newVal);
273         if (!norefresh) holdingsSvc.fetch({
274             rid : $scope.record_id,
275             org : $scope.holdings_ou,
276             copy: $scope.holdings_show_copies,
277             vol : $scope.holdings_show_vols,
278             empty: $scope.holdings_show_empty
279         }).then(function() {
280             $scope.holdingsGridDataProvider.refresh();
281         });
282     }
283
284     egCore.hatch.getItem('cat.holdings_show_vols').then(function(x){
285         if (typeof x ==  'undefined') x = true;
286         $scope.holdings_cb_changed('holdings_show_vols',x,true);
287         $('#holdings_show_vols').prop('checked', x);
288     }).then(function(){
289         egCore.hatch.getItem('cat.holdings_show_copies').then(function(x){
290             if (typeof x ==  'undefined') x = true;
291             $scope.holdings_cb_changed('holdings_show_copies',x,true);
292             $('#holdings_show_copies').prop('checked', x);
293         }).then(function(){
294             egCore.hatch.getItem('cat.holdings_show_empty').then(function(x){
295                 if (typeof x ==  'undefined') x = true;
296                 $scope.holdings_cb_changed('holdings_show_empty',x);
297                 $('#holdings_show_empty').prop('checked', x);
298             })
299         })
300     });
301
302     $scope.holdings_checkbox_handler = function (item) {
303         $scope.holdings_cb_changed(item.checkbox,item.checked);
304     }
305
306     function gatherSelectedHoldingsIds () {
307         var cp_id_list = [];
308         angular.forEach(
309             $scope.holdingsGridControls.selectedItems(),
310             function (item) { cp_id_list = cp_id_list.concat(item.id_list) }
311         );
312         return cp_id_list;
313     }
314
315     spawnHoldingsEdit = function (hide_vols,hide_copies){
316         egCore.net.request(
317             'open-ils.actor',
318             'open-ils.actor.anon_cache.set_value',
319             null, 'edit-these-copies', {
320                 record_id: $scope.record_id,
321                 copies: gatherSelectedHoldingsIds(),
322                 hide_vols : hide_vols,
323                 hide_copies : hide_copies
324             }
325         ).then(function(key) {
326             if (key) {
327                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
328                 $timeout(function() { $window.open(url, '_blank') });
329             } else {
330                 alert('Could not create anonymous cache key!');
331             }
332         });
333     }
334     $scope.selectedHoldingsVolCopyEdit = function () { spawnHoldingsEdit(false,false) }
335     $scope.selectedHoldingsVolEdit = function () { spawnHoldingsEdit(false,true) }
336     $scope.selectedHoldingsCopyEdit = function () { spawnHoldingsEdit(true,false) }
337
338     $scope.selectedHoldingsItemStatus = function (){
339         var url = egCore.env.basePath + 'cat/item/search/' + gatherSelectedHoldingsIds().join(',')
340         $timeout(function() { $window.open(url, '_blank') });
341     }
342
343     $scope.selectedHoldingsItemStatusDetail = function (){
344         angular.forEach(
345             gatherSelectedHoldingsIds(),
346             function (cid) {
347                 var url = egCore.env.basePath +
348                           'cat/item/' + cid;
349                 $timeout(function() { $window.open(url, '_blank') });
350             }
351         );
352     }
353
354     $scope.selectedHoldingsItemStatusTgrEvt = function (){
355         angular.forEach(
356             gatherSelectedHoldingsIds(),
357             function (cid) {
358                 var url = egCore.env.basePath +
359                           'cat/item/' + cid + '/triggered_events';
360                 $timeout(function() { $window.open(url, '_blank') });
361             }
362         );
363     }
364
365     $scope.selectedHoldingsItemStatusHolds = function (){
366         angular.forEach(
367             gatherSelectedHoldingsIds(),
368             function (cid) {
369                 var url = egCore.env.basePath +
370                           'cat/item/' + cid + '/holds';
371                 $timeout(function() { $window.open(url, '_blank') });
372             }
373         );
374     }
375
376     $scope.selectedHoldingsDamaged = function () {
377         egCirc.mark_damaged(gatherSelectedHoldingsIds()).then(function() {
378             holdingsSvc.fetch({
379                 rid : $scope.record_id,
380                 org : $scope.holdings_ou,
381                 copy: $scope.holdings_show_copies,
382                 vol : $scope.holdings_show_vols,
383                 empty: $scope.holdings_show_empty
384             }).then(function() {
385                 $scope.holdingsGridDataProvider.refresh();
386             });
387         });
388     }
389
390     $scope.selectedHoldingsMissing = function () {
391         egCirc.mark_missing(gatherSelectedHoldingsIds()).then(function() {
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
404
405     // ------------------------------------------------------------------
406     // Holds 
407     var provider = egGridDataProvider.instance({});
408     $scope.hold_grid_data_provider = provider;
409     $scope.grid_actions = egHoldGridActions;
410     $scope.grid_actions.refresh = function () { provider.refresh() };
411     $scope.hold_grid_controls = {};
412
413     var hold_ids = []; // current list of holds
414     function fetchHolds(offset, count) {
415         var ids = hold_ids.slice(offset, offset + count);
416         return egHolds.fetch_holds(ids).then(null, null,
417             function(hold_data) { 
418                 return hold_data;
419             }
420         );
421     }
422
423     provider.get = function(offset, count) {
424         if ($scope.record_tab != 'holds') return $q.when();
425         var deferred = $q.defer();
426         hold_ids = []; // no caching ATM
427
428         // fetch the IDs
429         egCore.net.request(
430             'open-ils.circ',
431             'open-ils.circ.holds.retrieve_all_from_title',
432             egCore.auth.token(), $scope.record_id, 
433             {pickup_lib : egCore.org.descendants($scope.pickup_ou.id(), true)}
434         ).then(
435             function(hold_data) {
436                 angular.forEach(hold_data, function(list, type) {
437                     hold_ids = hold_ids.concat(list);
438                 });
439                 fetchHolds(offset, count).then(
440                     deferred.resolve, null, deferred.notify);
441             }
442         );
443
444         return deferred.promise;
445     }
446
447     $scope.detail_view = function(action, user_data, items) {
448         if (h = items[0]) {
449             $scope.detail_hold_id = h.hold.id();
450         }
451     }
452
453     $scope.list_view = function(items) {
454          $scope.detail_hold_id = null;
455     }
456
457     // refresh the list of record holds when the pickup lib is changed.
458     $scope.pickup_ou = egCore.org.get(egCore.auth.user().ws_ou());
459     $scope.pickup_ou_changed = function(org) {
460         $scope.pickup_ou = org;
461         provider.refresh();
462     }
463
464     $scope.print_holds = function() {
465         var holds = [];
466         angular.forEach($scope.hold_grid_controls.allItems(), function(item) {
467             holds.push({
468                 hold : egCore.idl.toHash(item.hold),
469                 patron_last : item.patron_last,
470                 patron_alias : item.patron_alias,
471                 patron_barcode : item.patron_barcode,
472                 copy : egCore.idl.toHash(item.copy),
473                 volume : egCore.idl.toHash(item.volume),
474                 title : item.mvr.title(),
475                 author : item.mvr.author()
476             });
477         });
478
479         egCore.print.print({
480             context : 'receipt', 
481             template : 'holds_for_bib', 
482             scope : {holds : holds}
483         });
484     }
485
486     $scope.mark_hold_transfer_dest = function() {
487         egCore.hatch.setLocalItem(
488             'eg.circ.hold.title_transfer_target', $scope.record_id);
489     }
490
491     // UI presents this option as "all holds"
492     $scope.transfer_holds_to_marked = function() {
493         var hold_ids = $scope.hold_grid_controls.allItems().map(
494             function(hold_data) {return hold_data.hold.id()});
495         egHolds.transfer_to_marked_title(hold_ids);
496     }
497
498     // ------------------------------------------------------------------
499     // Initialize the selected tab
500
501     function init_cat_url() {
502         // Set the initial catalog URL.  This only happens once.
503         // The URL is otherwise generated through user navigation.
504         if ($scope.catalog_url) return; 
505
506         var url = $location.absUrl().replace(/\/staff.*/, '/opac/advanced');
507
508         // A record ID in the path indicates a request for the record-
509         // specific page.
510         if ($routeParams.record_id) {
511             url = url.replace(/advanced/, '/record/' + $scope.record_id);
512         }
513
514         $scope.catalog_url = url;
515     }
516
517     function init_parts_url() {
518         $scope.parts_url = $location
519             .absUrl()
520             .replace(
521                 /\/staff.*/,
522                 '/conify/global/biblio/monograph_part?r='+$scope.record_id
523             );
524     }
525
526     $scope.set_record_tab = function(tab) {
527         $scope.record_tab = tab;
528
529         switch(tab) {
530
531             case 'monoparts':
532                 init_parts_url();
533                 break;
534
535             case 'catalog':
536                 init_cat_url();
537                 break;
538
539             case 'holds':
540                 $scope.detail_hold_record_id = $scope.record_id; 
541                 // refresh the holds grid
542                 provider.refresh();
543                 break;
544         }
545     }
546
547     $scope.set_default_record_tab = function() {
548         egCore.hatch.setLocalItem(
549             'eg.cat.default_record_tab', $scope.record_tab);
550         $timeout(function(){$scope.default_tab = $scope.record_tab});
551     }
552
553     var tab;
554     if ($scope.record_id) {
555         $scope.default_tab = egCore.hatch.getLocalItem( 'eg.cat.default_record_tab' );
556         tab = $routeParams.record_tab || $scope.default_tab || 'catalog';
557
558     } else {
559         tab = $routeParams.record_tab || 'catalog';
560     }
561     $scope.set_record_tab(tab);
562
563 }])
564
565 .controller('URLVerifyCtrl',
566        ['$scope','$location',
567 function($scope , $location) {
568     $scope.verifyurls_url = $location.absUrl().replace(/\/staff.*/, '/url_verify/sessions');
569 }])
570
571 .controller('VandelayCtrl',
572        ['$scope','$location',
573 function($scope , $location) {
574     $scope.vandelay_url = $location.absUrl().replace(/\/staff.*/, '/vandelay/vandelay');
575 }])
576
577 .controller('ManageAuthoritiesCtrl',
578        ['$scope','$location',
579 function($scope , $location) {
580     $scope.manageauthorities_url = $location.absUrl().replace(/\/staff.*/, '/cat/authority/list');
581 }])
582
583 .controller('BatchEditCtrl',
584        ['$scope','$location','$routeParams',
585 function($scope , $location , $routeParams) {
586     $scope.batchedit_url = $location.absUrl().replace(/\/eg.*/, '/opac/extras/merge_template');
587     if ($routeParams.container_type) {
588         switch ($routeParams.container_type) {
589             case 'bucket':
590                 $scope.batchedit_url += '?recordSource=b&containerid=' + $routeParams.container_id;
591                 break;
592             case 'record':
593                 $scope.batchedit_url += '?recordSource=r&recid=' + $routeParams.container_id;
594                 break;
595         };
596     }
597 }])
598
599  
600 .filter('boolText', function(){
601     return function (v) {
602         return v == 't';
603     }
604 })
605
606 .factory('holdingsSvc', 
607        ['egCore','$q',
608 function(egCore , $q) {
609
610     var service = {
611         ongoing : false,
612         copies : [], // record search results
613         index : 0, // search grid index
614         org : null,
615         rid : null
616     };
617
618     service.flesh = {   
619         flesh : 2, 
620         flesh_fields : {
621             acp : ['status','location'],
622             acn : ['prefix','suffix','copies']
623         }
624     }
625
626     // resolved with the last received copy
627     service.fetch = function(opts) {
628         if (service.ongoing) {
629             console.log('Skipping fetch, ongoing = true');
630             return $q.when();
631         }
632
633         var rid = opts.rid;
634         var org = opts.org;
635         var copy = opts.copy;
636         var vol = opts.vol;
637         var empty = opts.empty;
638
639         if (!rid) return $q.when();
640         if (!org) return $q.when();
641
642         service.ongoing = true;
643
644         service.rid = rid;
645         service.org = org;
646         service.copies = [];
647         service.index = 0;
648
649         var org_list = egCore.org.descendants(org.id(), true);
650         console.log('Holdings fetch with: rid='+rid+' org='+org_list+' copy='+copy+' vol='+vol+' empty='+empty);
651
652         return egCore.pcrud.search(
653             'acn',
654             {record : rid, owning_lib : org_list, deleted : 'f'},
655             service.flesh
656         ).then(
657             function() { // finished
658                 service.copies = service.copies.sort(
659                     function (a, b) {
660                         function compare_array (x, y, i) {
661                             if (x[i] && y[i]) { // both have values
662                                 if (x[i] == y[i]) { // need to look deeper
663                                     return compare_array(x, y, ++i);
664                                 }
665
666                                 if (x[i] < y[i]) { // x is first
667                                     return -1;
668                                 } else if (x[i] > y[i]) { // y is first
669                                     return 1;
670                                 }
671
672                             } else { // no orgs to compare ...
673                                 if (x[i]) return -1;
674                                 if (y[i]) return 1;
675                             }
676                             return 0;
677                         }
678
679                         var owner_order = compare_array(a.owner_list, b.owner_list, 0);
680                         if (!owner_order) {
681                             // now compare on CN label
682                             if (a.call_number.label < b.call_number.label) return -1;
683                             if (a.call_number.label > b.call_number.label) return 1;
684
685                             // try copy number
686                             if (a.copy_number < b.copy_number) return -1;
687                             if (a.copy_number > b.copy_number) return 1;
688
689                             // finally, barcode
690                             if (a.barcode < b.barcode) return -1;
691                             if (a.barcode > b.barcode) return 1;
692                         }
693                         return owner_order;
694                     }
695                 );
696
697                 // create a label using just the unique part of the owner list
698                 var index = 0;
699                 var prev_owner_list;
700                 angular.forEach(service.copies, function (cp) {
701                     if (!prev_owner_list) {
702                         cp.owner_label = cp.owner_list.join(' ... ');
703                     } else {
704                         var current_owner_list = cp.owner_list.slice();
705                         while (current_owner_list[1] && prev_owner_list[1] && current_owner_list[0] == prev_owner_list[0]) {
706                             current_owner_list.shift();
707                             prev_owner_list.shift();
708                         }
709                         cp.owner_label = current_owner_list.join(' ... ');
710                     }
711
712                     cp.index = index++;
713                     prev_owner_list = cp.owner_list.slice();
714                 });
715
716                 var new_list = service.copies;
717                 if (!copy || !vol) { // collapse copy rows, supply a count instead
718
719                     index = 0;
720                     var cp_list = [];
721                     var prev_key;
722                     var current_blob = {};
723                     angular.forEach(new_list, function (cp) {
724                         if (!prev_key) {
725                             prev_key = cp.owner_list.join('') + cp.call_number.label;
726                             if (cp.barcode) current_blob.copy_count = 1;
727                             current_blob.index = index++;
728                             current_blob.id_list = cp.id_list;
729                             current_blob.call_number = cp.call_number;
730                             current_blob.owner_list = cp.owner_list;
731                             current_blob.owner_label = cp.owner_label;
732                         } else {
733                             var current_key = cp.owner_list.join('') + cp.call_number.label;
734                             if (prev_key == current_key) { // collapse into current_blob
735                                 current_blob.copy_count++;
736                                 current_blob.id_list = current_blob.id_list.concat(cp.id_list);
737                             } else {
738                                 current_blob.barcode = current_blob.copy_count;
739                                 cp_list.push(current_blob);
740                                 prev_key = current_key;
741                                 current_blob = {};
742                                 if (cp.barcode) current_blob.copy_count = 1;
743                                 current_blob.index = index++;
744                                 current_blob.id_list = cp.id_list;
745                                 current_blob.owner_label = cp.owner_label;
746                                 current_blob.call_number = cp.call_number;
747                                 current_blob.owner_list = cp.owner_list;
748                             }
749                         }
750                     });
751
752                     current_blob.barcode = current_blob.copy_count;
753                     cp_list.push(current_blob);
754                     new_list = cp_list;
755
756                     if (!vol) { // do the same for vol rows
757
758                         index = 0;
759                         var cn_list = [];
760                         prev_key = '';
761                         var current_blob = {};
762                         angular.forEach(cp_list, function (cp) {
763                             if (!prev_key) {
764                                 prev_key = cp.owner_list.join('');
765                                 current_blob.index = index++;
766                                 current_blob.id_list = cp.id_list;
767                                 current_blob.cn_count = 1;
768                                 current_blob.copy_count = cp.copy_count;
769                                 current_blob.owner_list = cp.owner_list;
770                                 current_blob.owner_label = cp.owner_label;
771                             } else {
772                                 var current_key = cp.owner_list.join('');
773                                 if (prev_key == current_key) { // collapse into current_blob
774                                     current_blob.cn_count++;
775                                     current_blob.copy_count += cp.copy_count;
776                                     current_blob.id_list = current_blob.id_list.concat(cp.id_list);
777                                 } else {
778                                     current_blob.barcode = current_blob.copy_count;
779                                     current_blob.call_number = { label : current_blob.cn_count };
780                                     cn_list.push(current_blob);
781                                     prev_key = current_key;
782                                     current_blob = {};
783                                     current_blob.index = index++;
784                                     current_blob.id_list = cp.id_list;
785                                     current_blob.owner_label = cp.owner_label;
786                                     current_blob.cn_count = 1;
787                                     current_blob.copy_count = cp.copy_count;
788                                     current_blob.owner_list = cp.owner_list;
789                                 }
790                             }
791                         });
792     
793                         current_blob.barcode = current_blob.copy_count;
794                         current_blob.call_number = { label : current_blob.cn_count };
795                         cn_list.push(current_blob);
796                         new_list = cn_list;
797     
798                     }
799                 }
800
801                 service.copies = new_list;
802                 service.ongoing = false;
803             },
804
805             null, // error
806
807             // notify reads the stream of copies, one at a time.
808             function(cn) {
809
810                 var copies = cn.copies();
811                 cn.copies([]);
812
813                 angular.forEach(copies, function (cp) {
814                     cp.call_number(cn);
815                 });
816
817                 var flat = egCore.idl.toHash(copies);
818                 if (flat[0]) {
819                     var owner = egCore.org.get(flat[0].call_number.owning_lib);
820
821                     var owner_name_list = [];
822                     while (owner.parent_ou()) { // we're going to skip the top of the tree...
823                         owner_name_list.unshift(owner.name());
824                         owner = egCore.org.get(owner.parent_ou());
825                     }
826
827                     angular.forEach(flat, function (cp) {
828                         cp.owner_list = owner_name_list;
829                         cp.id_list = [cp.id];
830                     });
831
832                     service.copies = service.copies.concat(flat);
833
834                     if (empty && flat.length == 0) {
835                         service.copies.push({
836                             owner_list : owner_name_list,
837                             call_number: egCore.idl.toHash(cn)
838                         });
839                     }
840                 }
841
842                 return cn;
843             }
844         );
845     }
846
847     return service;
848 }])
849
850