d07c598e81a8273fc24eb6fe0e382549024008ed
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / services / item.js
1 /**
2  * Shared item services for circulation
3  */
4
5 angular.module('egCoreMod')
6     .factory('egItem',
7        ['egCore','egOrg','egCirc','$uibModal','$q','$timeout','$window','ngToast','egConfirmDialog','egAlertDialog',
8 function(egCore , egOrg , egCirc , $uibModal , $q , $timeout , $window , ngToast , egConfirmDialog , egAlertDialog ) {
9
10     var service = {
11         copies : [], // copy barcode search results
12         index : 0 // search grid index
13     };
14
15     service.flesh = {   
16         flesh : 4,
17         flesh_fields : {
18             acp : ['call_number','location','status','floating','circ_modifier',
19                 'age_protect','circ_lib','copy_alerts', 'creator', 'editor', 'circ_as_type', 'latest_inventory'],
20             acn : ['record','prefix','suffix','label_class'],
21             bre : ['simple_record','creator','editor'],
22             alci : ['inventory_workstation']
23         },
24         select : { 
25             // avoid fleshing MARC on the bre
26             // note: don't add simple_record.. not sure why
27             bre : ['id','tcn_value','creator','editor', 'create_date', 'edit_date'],
28         } 
29     }
30
31     service.circFlesh = {
32         flesh : 2,
33         flesh_fields : {
34             combcirc : [
35                 'usr',
36                 'workstation',
37                 'checkin_workstation',
38                 'checkin_lib',
39                 'duration_rule',
40                 'max_fine_rule',
41                 'recurring_fine_rule'
42             ],
43             au : ['card']
44         },
45         order_by : {combcirc : 'xact_start desc'},
46         limit :  1
47     }
48
49     //Retrieve separate copy, aacs, and accs information
50     service.getCopy = function(barcode, id) {
51         if (barcode) {
52             // handle barcode completion
53             return egCirc.handle_barcode_completion(barcode)
54             .then(function(actual_barcode) {
55                 return egCore.pcrud.search(
56                     'acp', {barcode : actual_barcode, deleted : 'f'},
57                     service.flesh).then(function(copy) {return copy});
58             });
59         }
60
61         return egCore.pcrud.retrieve( 'acp', id, service.flesh)
62             .then(function(copy) {return copy});
63     }
64
65     service.getCirc = function(id) {
66         return egCore.pcrud.search('combcirc', { target_copy : id },
67             service.circFlesh).then(function(circ) {return circ});
68     }
69
70     service.getSummary = function(id) {
71         return circ_summary = egCore.net.request(
72             'open-ils.circ',
73             'open-ils.circ.renewal_chain.retrieve_by_circ.summary',
74             egCore.auth.token(), id).then(
75                 function(circ_summary) {return circ_summary});
76     }
77
78     //Combine copy, circ, and accs information
79     service.retrieveCopyData = function(barcode, id) {
80         var copyData = {};
81
82         var fetchCopy = function(barcode, id) {
83             return service.getCopy(barcode, id)
84                 .then(function(copy) {
85                     copyData.copy = copy;
86                     return copyData;
87                 });
88         }
89         var fetchCirc = function(copy) {
90             return service.getCirc(copy.id())
91                 .then(function(circ) {
92                     copyData.circ = circ;
93                     return copyData;
94                 });
95         }
96         var fetchSummary = function(circ) {
97             return service.getSummary(circ.id())
98                 .then(function(summary) {
99                     copyData.circ_summary = summary;
100                     return copyData;
101                 });
102         }
103
104         return fetchCopy(barcode, id).then(function(res) {
105
106             if(!res.copy) { return $q.when(); }
107             return fetchCirc(copyData.copy).then(function(res) {
108                 if (copyData.circ) {
109                     return fetchSummary(copyData.circ).then(function() {
110                         return copyData;
111                     });
112                 } else {
113                     return copyData;
114                 }
115             });
116         });
117
118     }
119
120     // resolved with the last received copy
121     service.fetch = function(barcode, id, noListDupes) {
122         var copy;
123         var circ;
124         var circ_summary;
125         var lastRes = {};
126
127         return service.retrieveCopyData(barcode, id)
128         .then(function(copyData) {
129             if(!copyData) { return $q.when(); }
130             //Make sure we're getting a completed copyData - no plain acp or circ objects
131             if (copyData.circ) {
132                 // flesh circ_lib locally
133                 copyData.circ.circ_lib(egCore.org.get(copyData.circ.circ_lib()));
134
135             }
136             var flatCopy;
137
138             if (noListDupes) {
139                 // use the existing copy if possible
140                 flatCopy = service.copies.filter(
141                     function(c) {return c.id == copyData.copy.id()})[0];
142             }
143
144             // flesh acn.owning_lib
145             copyData.copy.call_number().owning_lib(egCore.org.get(copyData.copy.call_number().owning_lib()));
146
147             if (!flatCopy) {
148                 flatCopy = egCore.idl.toHash(copyData.copy, true);
149
150                 if (copyData.circ) {
151                     flatCopy._circ = egCore.idl.toHash(copyData.circ, true);
152                     flatCopy._circ_summary = egCore.idl.toHash(copyData.circ_summary, true);
153                     flatCopy._circ_lib = copyData.circ.circ_lib();
154                     flatCopy._duration = copyData.circ.duration();
155                     flatCopy._circ_ws = flatCopy._circ_summary.last_renewal_workstation ?
156                                         flatCopy._circ_summary.last_renewal_workstation :
157                                         flatCopy._circ_summary.checkout_workstation ?
158                                         flatCopy._circ_summary.checkout_workstation :
159                                         '';
160                 }
161                 flatCopy.index = service.index++;
162                 flatCopy.copy_alert_count = copyData.copy.copy_alerts().filter(function(aca) {
163                     return !aca.ack_time();
164                 }).length;
165
166                 service.copies.unshift(flatCopy);
167             }
168
169             //Get in-house use count
170             egCore.pcrud.search('aihu',
171                 {item : flatCopy.id}, {}, {idlist : true, atomic : true})
172             .then(function(uses) {
173                 flatCopy._inHouseUseCount = uses.length;
174                 copyData.copy._inHouseUseCount = uses.length;
175             });
176
177             //Get Monograph Parts
178             egCore.pcrud.search('acpm',
179                 {target_copy: flatCopy.id},
180                 { flesh : 1, flesh_fields : { acpm : ['part'] } },
181                 {atomic :true})
182             .then(function(acpm_array) {
183                 angular.forEach(acpm_array, function(acpm) {
184                     flatCopy.parts = egCore.idl.toHash(acpm.part());
185                     copyData.copy.parts = egCore.idl.toHash(acpm.part());
186                 });
187             });
188
189             return lastRes = {
190                 copy : copyData.copy,
191                 index : flatCopy.index
192             }
193         });
194
195
196     }
197
198     //all_items = selected grid rows, to be updated in place
199     service.updateInventory = function(copy_list, all_items) {
200         if (copy_list.length == 0) return;
201         return egCore.net.request(
202             'open-ils.circ',
203             'open-ils.circ.circulation.update_latest_inventory',
204             egCore.auth.token(), {copy_list: copy_list}
205         ).then(function(res) {
206             if (res) {
207                 if (all_items) angular.forEach(copy_list, function(copy) {
208                     angular.forEach(all_items, function(item) {
209                         if (copy == item.id) {
210                             egCore.pcrud.search('alci', {copy: copy},
211                               {flesh: 1, flesh_fields:
212                                 {alci: ['inventory_workstation']}
213                             }).then(function(alci) {
214                                 //update existing grid rows
215                                 item["latest_inventory.inventory_date"] = alci.inventory_date();
216                                 item["latest_inventory.inventory_workstation.name"] =
217                                     alci.inventory_workstation().name();
218                             });
219                         }
220                     });
221                 });
222                 return all_items || res;
223             }
224         });
225     }
226
227     service.add_copies_to_bucket = function(copy_list) {
228         if (copy_list.length == 0) return;
229
230         return $uibModal.open({
231             templateUrl: './cat/catalog/t_add_to_bucket',
232             backdrop: 'static',
233             animation: true,
234             size: 'md',
235             controller:
236                    ['$scope','$uibModalInstance',
237             function($scope , $uibModalInstance) {
238
239                 $scope.bucket_id = 0;
240                 $scope.newBucketName = '';
241                 $scope.allBuckets = [];
242
243                 egCore.net.request(
244                     'open-ils.actor',
245                     'open-ils.actor.container.retrieve_by_class.authoritative',
246                     egCore.auth.token(), egCore.auth.user().id(),
247                     'copy', 'staff_client'
248                 ).then(function(buckets) { $scope.allBuckets = buckets; });
249
250                 $scope.add_to_bucket = function() {
251                     var promises = [];
252                     angular.forEach(copy_list, function (cp) {
253                         var item = new egCore.idl.ccbi()
254                         item.bucket($scope.bucket_id);
255                         item.target_copy(cp);
256                         promises.push(
257                             egCore.net.request(
258                                 'open-ils.actor',
259                                 'open-ils.actor.container.item.create',
260                                 egCore.auth.token(), 'copy', item
261                             )
262                         );
263
264                         return $q.all(promises).then(function() {
265                             $uibModalInstance.close();
266                         });
267                     });
268                 }
269
270                 $scope.add_to_new_bucket = function() {
271                     var bucket = new egCore.idl.ccb();
272                     bucket.owner(egCore.auth.user().id());
273                     bucket.name($scope.newBucketName);
274                     bucket.description('');
275                     bucket.btype('staff_client');
276
277                     return egCore.net.request(
278                         'open-ils.actor',
279                         'open-ils.actor.container.create',
280                         egCore.auth.token(), 'copy', bucket
281                     ).then(function(bucket) {
282                         $scope.bucket_id = bucket;
283                         $scope.add_to_bucket();
284                     });
285                 }
286
287                 $scope.cancel = function() {
288                     $uibModalInstance.dismiss();
289                 }
290             }]
291         });
292     }
293
294     service.make_copies_bookable = function(items) {
295
296         var copies_by_record = {};
297         var record_list = [];
298         angular.forEach(
299             items,
300             function (item) {
301                 var record_id = item['call_number.record.id'];
302                 if (typeof copies_by_record[ record_id ] == 'undefined') {
303                     copies_by_record[ record_id ] = [];
304                     record_list.push( record_id );
305                 }
306                 copies_by_record[ record_id ].push(item.id);
307             }
308         );
309
310         var promises = [];
311         var combined_results = [];
312         angular.forEach(record_list, function(record_id) {
313             promises.push(
314                 egCore.net.request(
315                     'open-ils.booking',
316                     'open-ils.booking.resources.create_from_copies',
317                     egCore.auth.token(),
318                     copies_by_record[record_id]
319                 ).then(function(results) {
320                     if (results && results['brsrc']) {
321                         combined_results = combined_results.concat(results['brsrc']);
322                     }
323                 })
324             );
325         });
326
327         $q.all(promises).then(function() {
328             if (combined_results.length > 0) {
329                 $uibModal.open({
330                     template: '<eg-embed-frame url="booking_admin_url" handlers="funcs"></eg-embed-frame>',
331                     backdrop: 'static',
332                     animation: true,
333                     size: 'md',
334                     controller:
335                            ['$scope','$location','egCore','$uibModalInstance',
336                     function($scope , $location , egCore , $uibModalInstance) {
337
338                         $scope.funcs = {
339                             ses : egCore.auth.token(),
340                             resultant_brsrc : combined_results.map(function(o) { return o[0]; })
341                         }
342
343                         var booking_path = '/eg/conify/global/booking/resource';
344
345                         $scope.booking_admin_url =
346                             $location.absUrl().replace(/\/eg\/staff.*/, booking_path);
347                     }]
348                 });
349             }
350         });
351     }
352
353     service.book_copies_now = function(barcode) {
354         location.href = "/eg2/staff/booking/create_reservation/for_resource/" + barcode;
355     }
356
357     service.manage_reservations = function(barcode) {
358         location.href = "/eg2/staff/booking/manage_reservations/by_resource/" + barcode;
359     }
360
361     service.requestItems = function(copy_list,record_list) {
362         if (copy_list.length == 0) return;
363         if (record_list) {
364             record_list = record_list.filter(function(v,i,s){ // dedup
365                 return s.indexOf(v) == i;
366             });
367         }
368
369         return $uibModal.open({
370             templateUrl: './cat/catalog/t_request_items',
371             backdrop: 'static',
372             animation: true,
373             controller:
374                    ['$scope','$uibModalInstance','egUser',
375             function($scope , $uibModalInstance , egUser) {
376                 $scope.user = null;
377                 $scope.first_user_fetch = true;
378
379                 $scope.hold_data = {
380                     hold_type : 'C',
381                     copy_list : copy_list,
382                     record_list : record_list,
383                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
384                     user      : egCore.auth.user().id(),
385                     honor_user_settings : 
386                         egCore.hatch.getLocalItem('eg.cat.request_items.honor_user_settings')
387                 };
388
389                 egUser.get( $scope.hold_data.user ).then(function(u) {
390                     $scope.user = u;
391                     $scope.barcode = u.card().barcode();
392                     $scope.user_name = egUser.format_name(u);
393                     $scope.hold_data.user = u.id();
394                 });
395
396                 $scope.user_name = '';
397                 $scope.barcode = '';
398                 function user_preferred_pickup_lib(u) {
399                     var pickup_lib = u.home_ou();
400                     angular.forEach(u.settings(), function (s) {
401                         if (s.name() == "opac.default_pickup_location") {
402                             pickup_lib = s.value();
403                         }
404                     });
405                     return egOrg.get(pickup_lib);
406                 }
407                 $scope.$watch('barcode', function (n) {
408                     if (!$scope.first_user_fetch) {
409                         egUser.getByBarcode(n).then(function(u) {
410                             $scope.user = u;
411                             $scope.user_name = egUser.format_name(u);
412                             $scope.hold_data.user = u.id();
413                             if ($scope.hold_data.honor_user_settings) {
414                                 $scope.hold_data.pickup_lib = user_preferred_pickup_lib(u);
415                             }
416                         }, function() {
417                             $scope.user = null;
418                             $scope.user_name = '';
419                             delete $scope.hold_data.user;
420                         });
421                     }
422                     $scope.first_user_fetch = false;
423                 });
424                 $scope.$watch('hold_data.honor_user_settings', function (n) {
425                     if (n && $scope.user) {
426                         $scope.hold_data.pickup_lib = user_preferred_pickup_lib($scope.user);
427                     } else {
428                         $scope.hold_data.pickup_lib = egCore.org.get(egCore.auth.user().ws_ou());
429                     }
430                     egCore.hatch.setLocalItem('eg.cat.request_items.honor_user_settings',n);
431                 });
432
433                 $scope.ok = function(h) {
434                     var args = {
435                         patronid  : h.user,
436                         hold_type : h.hold_type,
437                         pickup_lib: h.pickup_lib.id(),
438                         depth     : 0
439                     };
440
441                     egCore.net.request(
442                         'open-ils.circ',
443                         'open-ils.circ.holds.test_and_create.batch.override',
444                         egCore.auth.token(), args,
445                         h.hold_type == 'T' ? h.record_list : h.copy_list,
446                         { 'all' : 1, 'honor_user_settings' : h.honor_user_settings }
447                     ).then(function(r) {
448                         console.log('request result',r);
449                         if (isNaN(r.result)) {
450                             if (typeof r.result.desc != 'undefined') {
451                                 ngToast.danger(r.result.desc);
452                             } else {
453                                 if (typeof r.result.last_event != 'undefined') {
454                                     ngToast.danger(r.result.last_event.desc);
455                                 } else {
456                                     ngToast.danger(egCore.strings.FAILURE_HOLD_REQUEST);
457                                 }
458                             }
459                         } else {
460                             ngToast.success(egCore.strings.SUCCESS_HOLD_REQUEST);
461                         }
462                     });
463
464                     $uibModalInstance.close();
465                 }
466
467                 $scope.cancel = function($event) {
468                     $uibModalInstance.dismiss();
469                     $event.preventDefault();
470                 }
471             }]
472         });
473     }
474
475     service.attach_to_peer_bib = function(items) {
476         if (items.length == 0) return;
477
478         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
479             if (!target_record) return;
480
481             return $uibModal.open({
482                 templateUrl: './cat/catalog/t_conjoined_selector',
483                 backdrop: 'static',
484                 animation: true,
485                 controller:
486                        ['$scope','$uibModalInstance',
487                 function($scope , $uibModalInstance) {
488                     $scope.update = false;
489
490                     $scope.peer_type = null;
491                     $scope.peer_type_list = [];
492
493                     get_peer_types = function() {
494                         if (egCore.env.bpt)
495                             return $q.when(egCore.env.bpt.list);
496
497                         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
498                         .then(function(list) {
499                             egCore.env.absorbList(list, 'bpt');
500                             return list;
501                         });
502                     }
503
504                     get_peer_types().then(function(list){
505                         $scope.peer_type_list = list;
506                     });
507
508                     $scope.ok = function(type) {
509                         var promises = [];
510
511                         angular.forEach(items, function (cp) {
512                             var n = new egCore.idl.bpbcm();
513                             n.isnew(true);
514                             n.peer_record(target_record);
515                             n.target_copy(cp.id);
516                             n.peer_type(type);
517                             promises.push(egCore.pcrud.create(n).then(function(){service.add_barcode_to_list(cp.barcode)}));
518                         });
519
520                         return $q.all(promises).then(function(){$uibModalInstance.close()});
521                     }
522
523                     $scope.cancel = function($event) {
524                         $uibModalInstance.dismiss();
525                         $event.preventDefault();
526                     }
527                 }]
528             });
529         });
530     }
531
532     service.selectedHoldingsCopyDelete = function (items) {
533         if (items.length == 0) return;
534
535         var copy_objects = [];
536         egCore.pcrud.search('acp',
537             {deleted : 'f', id : items.map(function(el){return el.id;}) },
538             { flesh : 1, flesh_fields : { acp : ['call_number'] } }
539         ).then(function() {
540
541             var cnHash = {};
542             var perCnCopies = {};
543
544             var cn_count = 0;
545             var cp_count = 0;
546
547             angular.forEach(
548                 copy_objects,
549                 function (cp) {
550                     cp.isdeleted(1);
551                     cp_count++;
552                     var cn_id = cp.call_number().id();
553                     if (!cnHash[cn_id]) {
554                         cnHash[cn_id] = cp.call_number();
555                         perCnCopies[cn_id] = [cp];
556                     } else {
557                         perCnCopies[cn_id].push(cp);
558                     }
559                     cp.call_number(cn_id); // prevent loops in JSON-ification
560                 }
561             );
562
563             angular.forEach(perCnCopies, function (v, k) {
564                 cnHash[k].copies(v);
565             });
566
567             cnList = [];
568             angular.forEach(cnHash, function (v, k) {
569                 cnList.push(v);
570             });
571
572             if (cnList.length == 0) return;
573
574             var flags = {};
575
576             egConfirmDialog.open(
577                 egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
578                 egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
579                 {copies : cp_count, volumes : cn_count}
580             ).result.then(function() {
581                 egCore.net.request(
582                     'open-ils.cat',
583                     'open-ils.cat.asset.volume.fleshed.batch.update',
584                     egCore.auth.token(), cnList, 1, flags
585                 ).then(function(resp){
586                     var evt = egCore.evt.parse(resp);
587                     if (evt) {
588                         egConfirmDialog.open(
589                             egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_TITLE,
590                             egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_BODY,
591                             {'evt_desc': evt.desc}
592                         ).result.then(function() {
593                             egCore.net.request(
594                                 'open-ils.cat',
595                                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
596                                 egCore.auth.token(), cnList, 1,
597                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
598                             ).then(function() {
599                                 angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
600                             });
601                         });
602                     } else {
603                         angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
604                     }
605                 });
606             });
607         },
608         null,
609         function(copy) {
610             copy_objects.push(copy);
611         });
612     }
613
614     service.checkin = function (items) {
615         angular.forEach(items, function (cp) {
616             egCirc.checkin({copy_barcode:cp.barcode}).then(
617                 function() { service.add_barcode_to_list(cp.barcode) }
618             );
619         });
620     }
621
622     service.renew = function (items) {
623         angular.forEach(items, function (cp) {
624             egCirc.renew({copy_barcode:cp.barcode}).then(
625                 function() { service.add_barcode_to_list(cp.barcode) }
626             );
627         });
628     }
629
630     service.cancel_transit = function (items) {
631         angular.forEach(items, function(cp) {
632             egCirc.find_copy_transit(null, {copy_barcode:cp.barcode})
633                 .then(function(t) { return egCirc.abort_transit(t.id())    })
634                 .then(function()  { return service.add_barcode_to_list(cp.barcode) });
635         });
636     }
637
638     service.selectedHoldingsDamaged = function (items) {
639         angular.forEach(items, function(cp) {
640             if (cp) {
641                 egCirc.mark_damaged({
642                     id: cp.id,
643                     barcode: cp.barcode,
644                     refresh: cp.refresh
645                 });
646             }
647         });
648     }
649
650     service.selectedHoldingsDiscard = function (items) {
651         egCirc.mark_discard(items.map(function(el){return {id : el.id, barcode : el.barcode};})).then(function(){
652             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
653         });
654     }
655
656     service.selectedHoldingsMissing = function (items) {
657         egCirc.mark_missing(items.map(function(el){return {id : el.id, barcode : el.barcode};})).then(function(){
658             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
659         });
660     }
661
662     service.gatherSelectedRecordIds = function (items) {
663         var rid_list = [];
664         angular.forEach(
665             items,
666             function (item) {
667                 if (rid_list.indexOf(item['call_number.record.id']) == -1)
668                     rid_list.push(item['call_number.record.id'])
669             }
670         );
671         return rid_list;
672     }
673
674     service.gatherSelectedVolumeIds = function (items,rid) {
675         var cn_id_list = [];
676         angular.forEach(
677             items,
678             function (item) {
679                 if (rid && item['call_number.record.id'] != rid) return;
680                 if (cn_id_list.indexOf(item['call_number.id']) == -1)
681                     cn_id_list.push(item['call_number.id'])
682             }
683         );
684         return cn_id_list;
685     }
686
687     service.gatherSelectedHoldingsIds = function (items,rid) {
688         var cp_id_list = [];
689         angular.forEach(
690             items,
691             function (item) {
692                 if (rid && item['call_number.record.id'] != rid) return;
693                 cp_id_list.push(item.id)
694             }
695         );
696         return cp_id_list;
697     }
698
699     service.spawnHoldingsAdd = function (items,use_vols,use_copies){
700         angular.forEach(service.gatherSelectedRecordIds(items), function (r) {
701             var raw = [];
702             if (use_copies) { // just a copy on existing volumes
703                 angular.forEach(service.gatherSelectedVolumeIds(items,r), function (v) {
704                     raw.push( {callnumber : v} );
705                 });
706             } else if (use_vols) {
707                 angular.forEach(
708                     service.gatherSelectedHoldingsIds(items,r),
709                     function (i) {
710                         angular.forEach(items, function(item) {
711                             if (i == item.id) raw.push({owner : item['call_number.owning_lib']});
712                         });
713                     }
714                 );
715             }
716
717             if (raw.length == 0) raw.push({});
718
719             egCore.net.request(
720                 'open-ils.actor',
721                 'open-ils.actor.anon_cache.set_value',
722                 null, 'edit-these-copies', {
723                     record_id: r,
724                     raw: raw,
725                     hide_vols : false,
726                     hide_copies : false
727                 }
728             ).then(function(key) {
729                 if (key) {
730                     var url = egCore.env.basePath + 'cat/volcopy/' + key;
731                     $timeout(function() { $window.open(url, '_blank') });
732                 } else {
733                     alert('Could not create anonymous cache key!');
734                 }
735             });
736         });
737     }
738
739     service.spawnHoldingsEdit = function (items,hide_vols,hide_copies){
740         var item_ids = [];
741         angular.forEach(items, function(i){
742             item_ids.push(i.id);
743         });
744
745         // provide record_id iff one record is selected.
746         // 0 disables record summary
747         var record_ids = service.gatherSelectedRecordIds(items);
748         var record_id  = record_ids.length === 1 ? record_ids[0] : 0;
749         egCore.net.request(
750             'open-ils.actor',
751             'open-ils.actor.anon_cache.set_value',
752             null,
753             'edit-these-copies',
754             {
755                 record_id: record_id,
756                 copies: item_ids,
757                 raw: {},
758                 hide_vols : hide_vols,
759                 hide_copies : hide_copies
760             }).then(function(key) {
761                 if (key) {
762                     var url = egCore.env.basePath + 'cat/volcopy/' + key;
763                     $timeout(function() { $window.open(url, '_blank') });
764                 } else {
765                     alert('Could not create anonymous cache key!');
766                 }
767             });
768     }
769
770     service.replaceBarcodes = function(items) {
771         angular.forEach(items, function (cp) {
772             $uibModal.open({
773                 templateUrl: './cat/share/t_replace_barcode',
774                 backdrop: 'static',
775                 animation: true,
776                 controller:
777                            ['$scope','$uibModalInstance',
778                     function($scope , $uibModalInstance) {
779                         $scope.isModal = true;
780                         $scope.focusBarcode = false;
781                         $scope.focusBarcode2 = true;
782                         $scope.barcode1 = cp.barcode;
783
784                         $scope.updateBarcode = function() {
785                             $scope.copyNotFound = false;
786                             $scope.updateOK = false;
787
788                             egCore.pcrud.search('acp',
789                                 {deleted : 'f', barcode : $scope.barcode1})
790                             .then(function(copy) {
791
792                                 if (!copy) {
793                                     $scope.focusBarcode = true;
794                                     $scope.copyNotFound = true;
795                                     return;
796                                 }
797
798                                 $scope.copyId = copy.id();
799                                 copy.barcode($scope.barcode2);
800
801                                 egCore.pcrud.update(copy).then(function(stat) {
802                                     $scope.updateOK = stat;
803                                     $scope.focusBarcode = true;
804                                     if (stat) service.add_barcode_to_list(copy.barcode());
805                                 });
806
807                             });
808                             $uibModalInstance.close();
809                         }
810
811                         $scope.cancel = function($event) {
812                             $uibModalInstance.dismiss();
813                             $event.preventDefault();
814                         }
815                     }
816                 ]
817             });
818         });
819     }
820
821     // this "transfers" selected copies to a new owning library,
822     // auto-creating volumes and deleting unused volumes as required.
823     service.changeItemOwningLib = function(items) {
824         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
825         if (!xfer_target || !items.length) {
826             return;
827         }
828         var vols_to_move   = {};
829         var copies_to_move = {};
830         angular.forEach(items, function(item) {
831             if (item['call_number.owning_lib'] != xfer_target) {
832                 if (item['call_number.id'] in vols_to_move) {
833                     copies_to_move[item['call_number.id']].push(item.id);
834                 } else {
835                     vols_to_move[item['call_number.id']] = {
836                         label       : item['call_number.label'],
837                         label_class : item['call_number.label_class'],
838                         record      : item['call_number.record.id'],
839                         prefix      : item['call_number.prefix.id'],
840                         suffix      : item['call_number.suffix.id']
841                     };
842                     copies_to_move[item['call_number.id']] = new Array;
843                     copies_to_move[item['call_number.id']].push(item.id);
844                 }
845             }
846         });
847
848         var promises = [];
849         angular.forEach(vols_to_move, function(vol, vol_id) {
850             promises.push(egCore.net.request(
851                 'open-ils.cat',
852                 'open-ils.cat.call_number.find_or_create',
853                 egCore.auth.token(),
854                 vol.label,
855                 vol.record,
856                 xfer_target,
857                 vol.prefix,
858                 vol.suffix,
859                 vol.label_class
860             ).then(function(resp) {
861                 var evt = egCore.evt.parse(resp);
862                 if (evt) return;
863                 return egCore.net.request(
864                     'open-ils.cat',
865                     'open-ils.cat.transfer_copies_to_volume',
866                     egCore.auth.token(),
867                     resp.acn_id,
868                     copies_to_move[vol_id]
869                 );
870             }));
871         });
872
873         $q.all(promises)
874         .then(
875             function() {
876                 angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
877             }
878         );
879     }
880
881     service.transferItems = function (items){
882         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
883         var copy_ids = service.gatherSelectedHoldingsIds(items);
884         if (xfer_target && copy_ids.length > 0) {
885             egCore.net.request(
886                 'open-ils.cat',
887                 'open-ils.cat.transfer_copies_to_volume',
888                 egCore.auth.token(),
889                 xfer_target,
890                 copy_ids
891             ).then(
892                 function(resp) { // oncomplete
893                     var evt = egCore.evt.parse(resp);
894                     if (evt) {
895                         egConfirmDialog.open(
896                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_TITLE,
897                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_BODY,
898                             {'evt_desc': evt}
899                         ).result.then(function() {
900                             egCore.net.request(
901                                 'open-ils.cat',
902                                 'open-ils.cat.transfer_copies_to_volume.override',
903                                 egCore.auth.token(),
904                                 xfer_target,
905                                 copy_ids,
906                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
907                             );
908                         }).then(function() {
909                             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
910                         });
911                     } else {
912                         angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
913                     }
914
915                 },
916                 null, // onerror
917                 null // onprogress
918             );
919         }
920     }
921
922     service.mark_missing_pieces = function(copy,outer_scope) {
923         var b = copy.barcode();
924         var t = egCore.idl.toHash(copy.call_number()).record.title;
925         egConfirmDialog.open(
926             egCore.strings.CONFIRM_MARK_MISSING_TITLE,
927             egCore.strings.CONFIRM_MARK_MISSING_BODY,
928             { barcode : b, title : t }
929         ).result.then(function() {
930
931             // kick off mark missing
932             return egCore.net.request(
933                 'open-ils.circ',
934                 'open-ils.circ.mark_item_missing_pieces',
935                 egCore.auth.token(), copy.id()
936             )
937
938         }).then(function(resp) {
939             var evt = egCore.evt.parse(resp); // should always produce event
940
941             if (evt.textcode == 'ACTION_CIRCULATION_NOT_FOUND') {
942                 return egAlertDialog.open(
943                     egCore.strings.CIRC_NOT_FOUND, {barcode : copy.barcode()});
944             }
945
946             var payload = evt.payload;
947
948             // TODO: open copy editor inline?  new tab?
949
950             // print the missing pieces slip
951             var promise = $q.when();
952             if (payload.slip) {
953                 // wait for completion, since it may spawn a confirm dialog
954                 promise = egCore.print.print({
955                     context : 'default',
956                     content_type : 'text/html',
957                     content : payload.slip.template_output().data()
958                 });
959             }
960
961             if (payload.letter) {
962                 outer_scope.letter = payload.letter.template_output().data();
963             }
964
965             // apply patron penalty
966             if (payload.circ) {
967                 promise.then(function() {
968                     egCirc.create_penalty(payload.circ.usr())
969                 });
970             }
971
972         });
973     }
974
975     service.print_spine_labels = function(copy_ids){
976         egCore.net.request(
977             'open-ils.actor',
978             'open-ils.actor.anon_cache.set_value',
979             null, 'print-labels-these-copies', {
980                 copies : copy_ids
981             }
982         ).then(function(key) {
983             if (key) {
984                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
985                 $timeout(function() { $window.open(url, '_blank') });
986             } else {
987                 alert('Could not create anonymous cache key!');
988             }
989         });
990     }
991
992     service.show_in_catalog = function(copy_list){
993         angular.forEach(copy_list, function(copy){
994             window.open('/eg/staff/cat/catalog/record/'+copy['call_number.record.id']+'/catalog', '_blank')
995         });
996     }
997
998     return service;
999 }])
1000 .filter('string_pick', function() { return function(i){ return arguments[i] || ''; }; })
1001