lp1760193 Add to Record Bucket from Item Status
[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(list, bucket_type) {
228         if (list.length == 0) return;
229         if (!bucket_type) bucket_type = 'copy';
230
231         return $uibModal.open({
232             templateUrl: './cat/catalog/t_add_to_bucket',
233             backdrop: 'static',
234             animation: true,
235             size: 'md',
236             controller:
237                    ['$scope','$uibModalInstance',
238             function($scope , $uibModalInstance) {
239
240                 $scope.bucket_id = 0;
241                 $scope.newBucketName = '';
242                 $scope.allBuckets = [];
243
244                 egCore.net.request(
245                     'open-ils.actor',
246                     'open-ils.actor.container.retrieve_by_class.authoritative',
247                     egCore.auth.token(), egCore.auth.user().id(),
248                     bucket_type, 'staff_client'
249                 ).then(function(buckets) { $scope.allBuckets = buckets; });
250
251                 $scope.add_to_bucket = function() {
252                     var promises = [];
253                     angular.forEach(list, function (entry) {
254                         var item = bucket_type == 'copy' ? new egCore.idl.ccbi() : new egCore.idl.cbrebi();
255                         item.bucket($scope.bucket_id);
256                         if (bucket_type == 'copy') item.target_copy(entry);
257                         if (bucket_type == 'biblio') item.target_biblio_record_entry(entry);
258                         promises.push(
259                             egCore.net.request(
260                                 'open-ils.actor',
261                                 'open-ils.actor.container.item.create',
262                                 egCore.auth.token(), bucket_type, item
263                             )
264                         );
265
266                         return $q.all(promises).then(function() {
267                             $uibModalInstance.close();
268                         });
269                     });
270                 }
271
272                 $scope.add_to_new_bucket = function() {
273                     var bucket = bucket_type == 'copy' ? new egCore.idl.ccb() : new egCore.idl.cbreb();
274                     bucket.owner(egCore.auth.user().id());
275                     bucket.name($scope.newBucketName);
276                     bucket.description('');
277                     bucket.btype('staff_client');
278
279                     return egCore.net.request(
280                         'open-ils.actor',
281                         'open-ils.actor.container.create',
282                         egCore.auth.token(), bucket_type, bucket
283                     ).then(function(bucket) {
284                         $scope.bucket_id = bucket;
285                         $scope.add_to_bucket();
286                     });
287                 }
288
289                 $scope.cancel = function() {
290                     $uibModalInstance.dismiss();
291                 }
292             }]
293         });
294     }
295
296     service.make_copies_bookable = function(items) {
297
298         var copies_by_record = {};
299         var record_list = [];
300         angular.forEach(
301             items,
302             function (item) {
303                 var record_id = item['call_number.record.id'];
304                 if (typeof copies_by_record[ record_id ] == 'undefined') {
305                     copies_by_record[ record_id ] = [];
306                     record_list.push( record_id );
307                 }
308                 copies_by_record[ record_id ].push(item.id);
309             }
310         );
311
312         var promises = [];
313         var combined_results = [];
314         angular.forEach(record_list, function(record_id) {
315             promises.push(
316                 egCore.net.request(
317                     'open-ils.booking',
318                     'open-ils.booking.resources.create_from_copies',
319                     egCore.auth.token(),
320                     copies_by_record[record_id]
321                 ).then(function(results) {
322                     if (results && results['brsrc']) {
323                         combined_results = combined_results.concat(results['brsrc']);
324                     }
325                 })
326             );
327         });
328
329         $q.all(promises).then(function() {
330             if (combined_results.length > 0) {
331                 $uibModal.open({
332                     template: '<eg-embed-frame url="booking_admin_url" handlers="funcs"></eg-embed-frame>',
333                     backdrop: 'static',
334                     animation: true,
335                     size: 'md',
336                     controller:
337                            ['$scope','$location','egCore','$uibModalInstance',
338                     function($scope , $location , egCore , $uibModalInstance) {
339
340                         $scope.funcs = {
341                             ses : egCore.auth.token(),
342                             resultant_brsrc : combined_results.map(function(o) { return o[0]; })
343                         }
344
345                         var booking_path = '/eg/conify/global/booking/resource';
346
347                         $scope.booking_admin_url =
348                             $location.absUrl().replace(/\/eg\/staff.*/, booking_path);
349                     }]
350                 });
351             }
352         });
353     }
354
355     service.book_copies_now = function(barcode) {
356         location.href = "/eg2/staff/booking/create_reservation/for_resource/" + barcode;
357     }
358
359     service.manage_reservations = function(barcode) {
360         location.href = "/eg2/staff/booking/manage_reservations/by_resource/" + barcode;
361     }
362
363     service.requestItems = function(copy_list,record_list) {
364         if (copy_list.length == 0) return;
365         if (record_list) {
366             record_list = record_list.filter(function(v,i,s){ // dedup
367                 return s.indexOf(v) == i;
368             });
369         }
370
371         return $uibModal.open({
372             templateUrl: './cat/catalog/t_request_items',
373             backdrop: 'static',
374             animation: true,
375             controller:
376                    ['$scope','$uibModalInstance','egUser',
377             function($scope , $uibModalInstance , egUser) {
378                 $scope.user = null;
379                 $scope.first_user_fetch = true;
380
381                 $scope.hold_data = {
382                     hold_type : 'C',
383                     copy_list : copy_list,
384                     record_list : record_list,
385                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
386                     user      : egCore.auth.user().id(),
387                     honor_user_settings : 
388                         egCore.hatch.getLocalItem('eg.cat.request_items.honor_user_settings')
389                 };
390
391                 egUser.get( $scope.hold_data.user ).then(function(u) {
392                     $scope.user = u;
393                     $scope.barcode = u.card().barcode();
394                     $scope.user_name = egUser.format_name(u);
395                     $scope.hold_data.user = u.id();
396                 });
397
398                 $scope.user_name = '';
399                 $scope.barcode = '';
400                 function user_preferred_pickup_lib(u) {
401                     var pickup_lib = u.home_ou();
402                     angular.forEach(u.settings(), function (s) {
403                         if (s.name() == "opac.default_pickup_location") {
404                             pickup_lib = s.value();
405                         }
406                     });
407                     return egOrg.get(pickup_lib);
408                 }
409                 $scope.$watch('barcode', function (n) {
410                     if (!$scope.first_user_fetch) {
411                         egUser.getByBarcode(n).then(function(u) {
412                             $scope.user = u;
413                             $scope.user_name = egUser.format_name(u);
414                             $scope.hold_data.user = u.id();
415                             if ($scope.hold_data.honor_user_settings) {
416                                 $scope.hold_data.pickup_lib = user_preferred_pickup_lib(u);
417                             }
418                         }, function() {
419                             $scope.user = null;
420                             $scope.user_name = '';
421                             delete $scope.hold_data.user;
422                         });
423                     }
424                     $scope.first_user_fetch = false;
425                 });
426                 $scope.$watch('hold_data.honor_user_settings', function (n) {
427                     if (n && $scope.user) {
428                         $scope.hold_data.pickup_lib = user_preferred_pickup_lib($scope.user);
429                     } else {
430                         $scope.hold_data.pickup_lib = egCore.org.get(egCore.auth.user().ws_ou());
431                     }
432                     egCore.hatch.setLocalItem('eg.cat.request_items.honor_user_settings',n);
433                 });
434
435                 $scope.ok = function(h) {
436                     var args = {
437                         patronid  : h.user,
438                         hold_type : h.hold_type,
439                         pickup_lib: h.pickup_lib.id(),
440                         depth     : 0
441                     };
442
443                     egCore.net.request(
444                         'open-ils.circ',
445                         'open-ils.circ.holds.test_and_create.batch.override',
446                         egCore.auth.token(), args,
447                         h.hold_type == 'T' ? h.record_list : h.copy_list,
448                         { 'all' : 1, 'honor_user_settings' : h.honor_user_settings }
449                     ).then(function(r) {
450                         console.log('request result',r);
451                         if (isNaN(r.result)) {
452                             if (typeof r.result.desc != 'undefined') {
453                                 ngToast.danger(r.result.desc);
454                             } else {
455                                 if (typeof r.result.last_event != 'undefined') {
456                                     ngToast.danger(r.result.last_event.desc);
457                                 } else {
458                                     ngToast.danger(egCore.strings.FAILURE_HOLD_REQUEST);
459                                 }
460                             }
461                         } else {
462                             ngToast.success(egCore.strings.SUCCESS_HOLD_REQUEST);
463                         }
464                     });
465
466                     $uibModalInstance.close();
467                 }
468
469                 $scope.cancel = function($event) {
470                     $uibModalInstance.dismiss();
471                     $event.preventDefault();
472                 }
473             }]
474         });
475     }
476
477     service.attach_to_peer_bib = function(items) {
478         if (items.length == 0) return;
479
480         egCore.hatch.getItem('eg.cat.marked_conjoined_record').then(function(target_record) {
481             if (!target_record) return;
482
483             return $uibModal.open({
484                 templateUrl: './cat/catalog/t_conjoined_selector',
485                 backdrop: 'static',
486                 animation: true,
487                 controller:
488                        ['$scope','$uibModalInstance',
489                 function($scope , $uibModalInstance) {
490                     $scope.update = false;
491
492                     $scope.peer_type = null;
493                     $scope.peer_type_list = [];
494
495                     get_peer_types = function() {
496                         if (egCore.env.bpt)
497                             return $q.when(egCore.env.bpt.list);
498
499                         return egCore.pcrud.retrieveAll('bpt', null, {atomic : true})
500                         .then(function(list) {
501                             egCore.env.absorbList(list, 'bpt');
502                             return list;
503                         });
504                     }
505
506                     get_peer_types().then(function(list){
507                         $scope.peer_type_list = list;
508                     });
509
510                     $scope.ok = function(type) {
511                         var promises = [];
512
513                         angular.forEach(items, function (cp) {
514                             var n = new egCore.idl.bpbcm();
515                             n.isnew(true);
516                             n.peer_record(target_record);
517                             n.target_copy(cp.id);
518                             n.peer_type(type);
519                             promises.push(egCore.pcrud.create(n).then(function(){service.add_barcode_to_list(cp.barcode)}));
520                         });
521
522                         return $q.all(promises).then(function(){$uibModalInstance.close()});
523                     }
524
525                     $scope.cancel = function($event) {
526                         $uibModalInstance.dismiss();
527                         $event.preventDefault();
528                     }
529                 }]
530             });
531         });
532     }
533
534     service.selectedHoldingsCopyDelete = function (items) {
535         if (items.length == 0) return;
536
537         var copy_objects = [];
538         egCore.pcrud.search('acp',
539             {deleted : 'f', id : items.map(function(el){return el.id;}) },
540             { flesh : 1, flesh_fields : { acp : ['call_number'] } }
541         ).then(function() {
542
543             var cnHash = {};
544             var perCnCopies = {};
545
546             var cn_count = 0;
547             var cp_count = 0;
548
549             angular.forEach(
550                 copy_objects,
551                 function (cp) {
552                     cp.isdeleted(1);
553                     cp_count++;
554                     var cn_id = cp.call_number().id();
555                     if (!cnHash[cn_id]) {
556                         cnHash[cn_id] = cp.call_number();
557                         perCnCopies[cn_id] = [cp];
558                     } else {
559                         perCnCopies[cn_id].push(cp);
560                     }
561                     cp.call_number(cn_id); // prevent loops in JSON-ification
562                 }
563             );
564
565             angular.forEach(perCnCopies, function (v, k) {
566                 cnHash[k].copies(v);
567             });
568
569             cnList = [];
570             angular.forEach(cnHash, function (v, k) {
571                 cnList.push(v);
572             });
573
574             if (cnList.length == 0) return;
575
576             var flags = {};
577
578             egConfirmDialog.open(
579                 egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES,
580                 egCore.strings.CONFIRM_DELETE_COPIES_VOLUMES_MESSAGE,
581                 {copies : cp_count, volumes : cn_count}
582             ).result.then(function() {
583                 egCore.net.request(
584                     'open-ils.cat',
585                     'open-ils.cat.asset.volume.fleshed.batch.update',
586                     egCore.auth.token(), cnList, 1, flags
587                 ).then(function(resp){
588                     var evt = egCore.evt.parse(resp);
589                     if (evt) {
590                         egConfirmDialog.open(
591                             egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_TITLE,
592                             egCore.strings.OVERRIDE_DELETE_ITEMS_FROM_CATALOG_BODY,
593                             {'evt_desc': evt.desc}
594                         ).result.then(function() {
595                             egCore.net.request(
596                                 'open-ils.cat',
597                                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
598                                 egCore.auth.token(), cnList, 1,
599                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
600                             ).then(function() {
601                                 angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
602                             });
603                         });
604                     } else {
605                         angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
606                     }
607                 });
608             });
609         },
610         null,
611         function(copy) {
612             copy_objects.push(copy);
613         });
614     }
615
616     service.checkin = function (items) {
617         angular.forEach(items, function (cp) {
618             egCirc.checkin({copy_barcode:cp.barcode}).then(
619                 function() { service.add_barcode_to_list(cp.barcode) }
620             );
621         });
622     }
623
624     service.renew = function (items) {
625         angular.forEach(items, function (cp) {
626             egCirc.renew({copy_barcode:cp.barcode}).then(
627                 function() { service.add_barcode_to_list(cp.barcode) }
628             );
629         });
630     }
631
632     service.cancel_transit = function (items) {
633         angular.forEach(items, function(cp) {
634             egCirc.find_copy_transit(null, {copy_barcode:cp.barcode})
635                 .then(function(t) { return egCirc.abort_transit(t.id())    })
636                 .then(function()  { return service.add_barcode_to_list(cp.barcode) });
637         });
638     }
639
640     service.selectedHoldingsDamaged = function (items) {
641         angular.forEach(items, function(cp) {
642             if (cp) {
643                 egCirc.mark_damaged({
644                     id: cp.id,
645                     barcode: cp.barcode,
646                     refresh: cp.refresh
647                 });
648             }
649         });
650     }
651
652     service.selectedHoldingsDiscard = function (items) {
653         egCirc.mark_discard(items.map(function(el){return {id : el.id, barcode : el.barcode};})).then(function(){
654             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
655         });
656     }
657
658     service.selectedHoldingsMissing = function (items) {
659         egCirc.mark_missing(items.map(function(el){return {id : el.id, barcode : el.barcode};})).then(function(){
660             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
661         });
662     }
663
664     service.gatherSelectedRecordIds = function (items) {
665         var rid_list = [];
666         angular.forEach(
667             items,
668             function (item) {
669                 if (rid_list.indexOf(item['call_number.record.id']) == -1)
670                     rid_list.push(item['call_number.record.id'])
671             }
672         );
673         return rid_list;
674     }
675
676     service.gatherSelectedVolumeIds = function (items,rid) {
677         var cn_id_list = [];
678         angular.forEach(
679             items,
680             function (item) {
681                 if (rid && item['call_number.record.id'] != rid) return;
682                 if (cn_id_list.indexOf(item['call_number.id']) == -1)
683                     cn_id_list.push(item['call_number.id'])
684             }
685         );
686         return cn_id_list;
687     }
688
689     service.gatherSelectedHoldingsIds = function (items,rid) {
690         var cp_id_list = [];
691         angular.forEach(
692             items,
693             function (item) {
694                 if (rid && item['call_number.record.id'] != rid) return;
695                 cp_id_list.push(item.id)
696             }
697         );
698         return cp_id_list;
699     }
700
701     service.spawnHoldingsAdd = function (items,use_vols,use_copies){
702         angular.forEach(service.gatherSelectedRecordIds(items), function (r) {
703             var raw = [];
704             if (use_copies) { // just a copy on existing volumes
705                 angular.forEach(service.gatherSelectedVolumeIds(items,r), function (v) {
706                     raw.push( {callnumber : v} );
707                 });
708             } else if (use_vols) {
709                 angular.forEach(
710                     service.gatherSelectedHoldingsIds(items,r),
711                     function (i) {
712                         angular.forEach(items, function(item) {
713                             if (i == item.id) raw.push({owner : item['call_number.owning_lib']});
714                         });
715                     }
716                 );
717             }
718
719             if (raw.length == 0) raw.push({});
720
721             egCore.net.request(
722                 'open-ils.actor',
723                 'open-ils.actor.anon_cache.set_value',
724                 null, 'edit-these-copies', {
725                     record_id: r,
726                     raw: raw,
727                     hide_vols : false,
728                     hide_copies : false
729                 }
730             ).then(function(key) {
731                 if (key) {
732                     var url = egCore.env.basePath + 'cat/volcopy/' + key;
733                     $timeout(function() { $window.open(url, '_blank') });
734                 } else {
735                     alert('Could not create anonymous cache key!');
736                 }
737             });
738         });
739     }
740
741     service.spawnHoldingsEdit = function (items,hide_vols,hide_copies){
742         var item_ids = [];
743         angular.forEach(items, function(i){
744             item_ids.push(i.id);
745         });
746
747         // provide record_id iff one record is selected.
748         // 0 disables record summary
749         var record_ids = service.gatherSelectedRecordIds(items);
750         var record_id  = record_ids.length === 1 ? record_ids[0] : 0;
751         egCore.net.request(
752             'open-ils.actor',
753             'open-ils.actor.anon_cache.set_value',
754             null,
755             'edit-these-copies',
756             {
757                 record_id: record_id,
758                 copies: item_ids,
759                 raw: {},
760                 hide_vols : hide_vols,
761                 hide_copies : hide_copies
762             }).then(function(key) {
763                 if (key) {
764                     var url = egCore.env.basePath + 'cat/volcopy/' + key;
765                     $timeout(function() { $window.open(url, '_blank') });
766                 } else {
767                     alert('Could not create anonymous cache key!');
768                 }
769             });
770     }
771
772     service.replaceBarcodes = function(items) {
773         angular.forEach(items, function (cp) {
774             $uibModal.open({
775                 templateUrl: './cat/share/t_replace_barcode',
776                 backdrop: 'static',
777                 animation: true,
778                 controller:
779                            ['$scope','$uibModalInstance',
780                     function($scope , $uibModalInstance) {
781                         $scope.isModal = true;
782                         $scope.focusBarcode = false;
783                         $scope.focusBarcode2 = true;
784                         $scope.barcode1 = cp.barcode;
785
786                         $scope.updateBarcode = function() {
787                             $scope.copyNotFound = false;
788                             $scope.updateOK = false;
789
790                             egCore.pcrud.search('acp',
791                                 {deleted : 'f', barcode : $scope.barcode1})
792                             .then(function(copy) {
793
794                                 if (!copy) {
795                                     $scope.focusBarcode = true;
796                                     $scope.copyNotFound = true;
797                                     return;
798                                 }
799
800                                 $scope.copyId = copy.id();
801                                 copy.barcode($scope.barcode2);
802
803                                 egCore.pcrud.update(copy).then(function(stat) {
804                                     $scope.updateOK = stat;
805                                     $scope.focusBarcode = true;
806                                     if (stat) service.add_barcode_to_list(copy.barcode());
807                                 });
808
809                             });
810                             $uibModalInstance.close();
811                         }
812
813                         $scope.cancel = function($event) {
814                             $uibModalInstance.dismiss();
815                             $event.preventDefault();
816                         }
817                     }
818                 ]
819             });
820         });
821     }
822
823     // this "transfers" selected copies to a new owning library,
824     // auto-creating volumes and deleting unused volumes as required.
825     service.changeItemOwningLib = function(items) {
826         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_lib');
827         if (!xfer_target || !items.length) {
828             return;
829         }
830         var vols_to_move   = {};
831         var copies_to_move = {};
832         angular.forEach(items, function(item) {
833             if (item['call_number.owning_lib'] != xfer_target) {
834                 if (item['call_number.id'] in vols_to_move) {
835                     copies_to_move[item['call_number.id']].push(item.id);
836                 } else {
837                     vols_to_move[item['call_number.id']] = {
838                         label       : item['call_number.label'],
839                         label_class : item['call_number.label_class'],
840                         record      : item['call_number.record.id'],
841                         prefix      : item['call_number.prefix.id'],
842                         suffix      : item['call_number.suffix.id']
843                     };
844                     copies_to_move[item['call_number.id']] = new Array;
845                     copies_to_move[item['call_number.id']].push(item.id);
846                 }
847             }
848         });
849
850         var promises = [];
851         angular.forEach(vols_to_move, function(vol, vol_id) {
852             promises.push(egCore.net.request(
853                 'open-ils.cat',
854                 'open-ils.cat.call_number.find_or_create',
855                 egCore.auth.token(),
856                 vol.label,
857                 vol.record,
858                 xfer_target,
859                 vol.prefix,
860                 vol.suffix,
861                 vol.label_class
862             ).then(function(resp) {
863                 var evt = egCore.evt.parse(resp);
864                 if (evt) return;
865                 return egCore.net.request(
866                     'open-ils.cat',
867                     'open-ils.cat.transfer_copies_to_volume',
868                     egCore.auth.token(),
869                     resp.acn_id,
870                     copies_to_move[vol_id]
871                 );
872             }));
873         });
874
875         $q.all(promises)
876         .then(
877             function() {
878                 angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
879             }
880         );
881     }
882
883     service.transferItems = function (items){
884         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
885         var copy_ids = service.gatherSelectedHoldingsIds(items);
886         if (xfer_target && copy_ids.length > 0) {
887             egCore.net.request(
888                 'open-ils.cat',
889                 'open-ils.cat.transfer_copies_to_volume',
890                 egCore.auth.token(),
891                 xfer_target,
892                 copy_ids
893             ).then(
894                 function(resp) { // oncomplete
895                     var evt = egCore.evt.parse(resp);
896                     if (evt) {
897                         egConfirmDialog.open(
898                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_TITLE,
899                             egCore.strings.OVERRIDE_TRANSFER_COPIES_TO_MARKED_VOLUME_BODY,
900                             {'evt_desc': evt}
901                         ).result.then(function() {
902                             egCore.net.request(
903                                 'open-ils.cat',
904                                 'open-ils.cat.transfer_copies_to_volume.override',
905                                 egCore.auth.token(),
906                                 xfer_target,
907                                 copy_ids,
908                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
909                             );
910                         }).then(function() {
911                             angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
912                         });
913                     } else {
914                         angular.forEach(items, function(cp){service.add_barcode_to_list(cp.barcode)});
915                     }
916
917                 },
918                 null, // onerror
919                 null // onprogress
920             );
921         }
922     }
923
924     service.mark_missing_pieces = function(copy,outer_scope) {
925         var b = copy.barcode();
926         var t = egCore.idl.toHash(copy.call_number()).record.title;
927         egConfirmDialog.open(
928             egCore.strings.CONFIRM_MARK_MISSING_TITLE,
929             egCore.strings.CONFIRM_MARK_MISSING_BODY,
930             { barcode : b, title : t }
931         ).result.then(function() {
932
933             // kick off mark missing
934             return egCore.net.request(
935                 'open-ils.circ',
936                 'open-ils.circ.mark_item_missing_pieces',
937                 egCore.auth.token(), copy.id()
938             )
939
940         }).then(function(resp) {
941             var evt = egCore.evt.parse(resp); // should always produce event
942
943             if (evt.textcode == 'ACTION_CIRCULATION_NOT_FOUND') {
944                 return egAlertDialog.open(
945                     egCore.strings.CIRC_NOT_FOUND, {barcode : copy.barcode()});
946             }
947
948             var payload = evt.payload;
949
950             // TODO: open copy editor inline?  new tab?
951
952             // print the missing pieces slip
953             var promise = $q.when();
954             if (payload.slip) {
955                 // wait for completion, since it may spawn a confirm dialog
956                 promise = egCore.print.print({
957                     context : 'default',
958                     content_type : 'text/html',
959                     content : payload.slip.template_output().data()
960                 });
961             }
962
963             if (payload.letter) {
964                 outer_scope.letter = payload.letter.template_output().data();
965             }
966
967             // apply patron penalty
968             if (payload.circ) {
969                 promise.then(function() {
970                     egCirc.create_penalty(payload.circ.usr())
971                 });
972             }
973
974         });
975     }
976
977     service.print_spine_labels = function(copy_ids){
978         egCore.net.request(
979             'open-ils.actor',
980             'open-ils.actor.anon_cache.set_value',
981             null, 'print-labels-these-copies', {
982                 copies : copy_ids
983             }
984         ).then(function(key) {
985             if (key) {
986                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
987                 $timeout(function() { $window.open(url, '_blank') });
988             } else {
989                 alert('Could not create anonymous cache key!');
990             }
991         });
992     }
993
994     service.show_in_catalog = function(copy_list){
995         angular.forEach(copy_list, function(copy){
996             window.open('/eg/staff/cat/catalog/record/'+copy['call_number.record.id']+'/catalog', '_blank')
997         });
998     }
999
1000     return service;
1001 }])
1002 .filter('string_pick', function() { return function(i){ return arguments[i] || ''; }; })
1003