lp1777675 inventory date support
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / bucket / copy / app.js
1 /**
2  * Copy Buckets
3  *
4  * Known Issues
5  *
6  * add-all actions only add visible/fetched items.
7  * remove all from bucket UI leaves busted pagination 
8  *   -- apply a refresh after item removal?
9  * problems with bucket view fetching by record ID instead of bucket item:
10  *   -- dupe bibs always sort to the bottom
11  *   -- dupe bibs result in more records displayed per page than requested
12  *   -- item 'pos' ordering is not honored on initial load.
13  */
14
15 angular.module('egCatCopyBuckets', 
16     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod'])
17
18 .config(function($routeProvider, $locationProvider, $compileProvider) {
19     $locationProvider.html5Mode(true);
20     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
21         
22     var resolver = {delay : function(egStartup) {return egStartup.go()}};
23
24     $routeProvider.when('/cat/bucket/copy/pending/:id', {
25         templateUrl: './cat/bucket/copy/t_pending',
26         controller: 'PendingCtrl',
27         resolve : resolver
28     });
29
30     $routeProvider.when('/cat/bucket/copy/pending', {
31         templateUrl: './cat/bucket/copy/t_pending',
32         controller: 'PendingCtrl',
33         resolve : resolver
34     });
35
36     $routeProvider.when('/cat/bucket/copy/view/:id', {
37         templateUrl: './cat/bucket/copy/t_view',
38         controller: 'ViewCtrl',
39         resolve : resolver
40     });
41
42     $routeProvider.when('/cat/bucket/copy/view', {
43         templateUrl: './cat/bucket/copy/t_view',
44         controller: 'ViewCtrl',
45         resolve : resolver
46     });
47
48     // default page / bucket view
49     $routeProvider.otherwise({redirectTo : '/cat/bucket/copy/view'});
50 })
51
52 /**
53  * bucketSvc allows us to communicate between the pending
54  * and view controllers.  It also allows us to cache
55  * data for each so that data reloads are not needed on every 
56  * tab click (i.e. route persistence).
57  */
58 .factory('bucketSvc', ['$q','egCore', function($q,  egCore) { 
59
60     var service = {
61         allBuckets : [], // un-fleshed user buckets
62         barcodeString : '', // last scanned barcode
63         barcodeRecords : [], // last scanned barcode results
64         currentBucket : null, // currently viewed bucket
65
66         // per-page list collections
67         pendingList : [],
68         viewList  : [],
69
70         // fetches all staff/copy buckets for the authenticated user
71         // this function may only be called after startup.
72         fetchUserBuckets : function(force) {
73             if (this.allBuckets.length && !force) return;
74             var self = this;
75             return egCore.net.request(
76                 'open-ils.actor',
77                 'open-ils.actor.container.retrieve_by_class.authoritative',
78                 egCore.auth.token(), egCore.auth.user().id(), 
79                 'copy', 'staff_client'
80             ).then(function(buckets) { self.allBuckets = buckets });
81         },
82
83         createBucket : function(name, desc) {
84             var deferred = $q.defer();
85             var bucket = new egCore.idl.ccb();
86             bucket.owner(egCore.auth.user().id());
87             bucket.name(name);
88             bucket.description(desc || '');
89             bucket.btype('staff_client');
90
91             egCore.net.request(
92                 'open-ils.actor',
93                 'open-ils.actor.container.create',
94                 egCore.auth.token(), 'copy', bucket
95             ).then(function(resp) {
96                 if (resp) {
97                     if (typeof resp == 'object') {
98                         console.error('bucket create error: ' + js2JSON(resp));
99                         deferred.reject();
100                     } else {
101                         deferred.resolve(resp);
102                     }
103                 }
104             });
105
106             return deferred.promise;
107         },
108
109         // edit the current bucket.  since we edit the 
110         // local object, there's no need to re-fetch.
111         editBucket : function(args) {
112             var bucket = service.currentBucket;
113             bucket.name(args.name);
114             bucket.description(args.desc);
115             bucket.pub(args.pub);
116             return egCore.net.request(
117                 'open-ils.actor',
118                 'open-ils.actor.container.update',
119                 egCore.auth.token(), 'copy', bucket
120             );
121         }
122     }
123
124     // returns 1 if full refresh is needed
125     // returns 2 if list refresh only is needed
126     service.bucketRefreshLevel = function(id) {
127         if (!service.currentBucket) return 1;
128         if (service.bucketNeedsRefresh) {
129             service.bucketNeedsRefresh = false;
130             service.currentBucket = null;
131             return 1;
132         }
133         if (service.currentBucket.id() != id) return 1;
134         return 2;
135     }
136
137     // returns a promise, resolved with bucket, rejected if bucket is
138     // not fetch-able
139     service.fetchBucket = function(id) {
140         var refresh = service.bucketRefreshLevel(id);
141         if (refresh == 2) return $q.when(service.currentBucket);
142
143         var deferred = $q.defer();
144
145         egCore.net.request(
146             'open-ils.actor',
147             'open-ils.actor.container.flesh.authoritative',
148             egCore.auth.token(), 'copy', id
149         ).then(function(bucket) {
150             var evt = egCore.evt.parse(bucket);
151             if (evt) {
152                 console.debug(evt);
153                 deferred.reject(evt);
154                 return;
155             }
156             egCore.pcrud.retrieve(
157                 'au', bucket.owner(),
158                 {flesh : 1, flesh_fields : {au : ["card"]}}
159             ).then(function(patron) {
160                 // On the off chance no barcode is present (it's not 
161                 // required) use the patron username as the identifier.
162                 bucket._owner_ident = patron.card() ? 
163                     patron.card().barcode() : patron.usrname();
164                 bucket._owner_name = patron.family_name();
165                 bucket._owner_ou = egCore.org.get(patron.home_ou()).shortname();
166             });
167
168             service.currentBucket = bucket;
169             deferred.resolve(bucket);
170         });
171
172         return deferred.promise;
173     }
174
175     // deletes a single container item from a bucket by container item ID.
176     // promise is rejected on failure
177     service.detachCopy = function(itemId) {
178         var deferred = $q.defer();
179         egCore.net.request(
180             'open-ils.actor',
181             'open-ils.actor.container.item.delete',
182             egCore.auth.token(), 'copy', itemId
183         ).then(function(resp) { 
184             var evt = egCore.evt.parse(resp);
185             if (evt) {
186                 console.error(evt);
187                 deferred.reject(evt);
188                 return;
189             }
190             console.log('detached bucket item ' + itemId);
191             deferred.resolve(resp);
192         });
193
194         return deferred.promise;
195     }
196
197     // delete bucket by ID.
198     // resolved w/ response on successful delete,
199     // rejected otherwise.
200     service.deleteBucket = function(id) {
201         var deferred = $q.defer();
202         egCore.net.request(
203             'open-ils.actor',
204             'open-ils.actor.container.full_delete',
205             egCore.auth.token(), 'copy', id
206         ).then(function(resp) {
207             var evt = egCore.evt.parse(resp);
208             if (evt) {
209                 console.error(evt);
210                 deferred.reject(evt);
211                 return;
212             }
213             deferred.resolve(resp);
214         });
215         return deferred.promise;
216     }
217
218     // apply last inventory data to fetched bucket items
219     service.fetchRecentInventoryData = function(copy) {
220         return egCore.pcrud.search('alci',
221             {copy: copy.id},
222             {flesh: 2, flesh_fields: {alci: ['inventory_workstation']}}
223         ).then(function(alci) {
224             return alci;
225         });
226     }
227
228     return service;
229 }])
230
231 /**
232  * Top-level controller.  
233  * Hosts functions needed by all controllers.
234  */
235 .controller('CopyBucketCtrl',
236        ['$scope','$location','$q','$timeout','$uibModal',
237         '$window','egCore','bucketSvc',
238 function($scope,  $location,  $q,  $timeout,  $uibModal,  
239          $window,  egCore,  bucketSvc) {
240
241     $scope.bucketSvc = bucketSvc;
242     $scope.bucket = function() { return bucketSvc.currentBucket }
243
244     // tabs: search, pending, view
245     $scope.setTab = function(tab) { 
246         $scope.tab = tab;
247
248         // for bucket selector; must be called after route resolve
249         bucketSvc.fetchUserBuckets(); 
250     };
251
252     $scope.loadBucketFromMenu = function(item, bucket) {
253         if (bucket) return $scope.loadBucket(bucket.id());
254     }
255
256     $scope.loadBucket = function(id) {
257         $location.path(
258             '/cat/bucket/copy/' + 
259                 $scope.tab + '/' + encodeURIComponent(id));
260     }
261
262     $scope.addToBucket = function(recs) {
263         if (recs.length == 0) return;
264         bucketSvc.bucketNeedsRefresh = true;
265
266         angular.forEach(recs,
267             function(rec) {
268                 var item = new egCore.idl.ccbi();
269                 item.bucket(bucketSvc.currentBucket.id());
270                 item.target_copy(rec.id);
271                 egCore.net.request(
272                     'open-ils.actor',
273                     'open-ils.actor.container.item.create', 
274                     egCore.auth.token(), 'copy', item
275                 ).then(function(resp) {
276
277                     // HACK: add the IDs of the added items so that the size
278                     // of the view list will grow (and update any UI looking at
279                     // the list size).  The data stored is inconsistent, but since
280                     // we are forcing a bucket refresh on the next rendering of 
281                     // the view pane, the list will be repaired.
282                     bucketSvc.currentBucket.items().push(resp);
283                 });
284             }
285         );
286     }
287
288     $scope.openCreateBucketDialog = function() {
289         $uibModal.open({
290             templateUrl: './cat/bucket/share/t_bucket_create',
291             backdrop: 'static',
292             controller: 
293                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
294                 $scope.focusMe = true;
295                 $scope.ok = function(args) { $uibModalInstance.close(args) }
296                 $scope.cancel = function () { $uibModalInstance.dismiss() }
297             }]
298         }).result.then(function (args) {
299             if (!args || !args.name) return;
300             bucketSvc.createBucket(args.name, args.desc).then(
301                 function(id) {
302                     if (!id) return;
303                     bucketSvc.viewList = [];
304                     bucketSvc.allBuckets = []; // reset
305                     bucketSvc.currentBucket = null;
306                     $location.path(
307                         '/cat/bucket/copy/' + $scope.tab + '/' + id);
308                 }
309             );
310         });
311     }
312
313     $scope.openEditBucketDialog = function() {
314         $uibModal.open({
315             templateUrl: './cat/bucket/share/t_bucket_edit',
316             backdrop: 'static',
317             controller: 
318                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
319                 $scope.focusMe = true;
320                 $scope.args = {
321                     name : bucketSvc.currentBucket.name(),
322                     desc : bucketSvc.currentBucket.description(),
323                     pub : bucketSvc.currentBucket.pub() == 't'
324                 };
325                 $scope.ok = function(args) { 
326                     if (!args) return;
327                     $scope.actionPending = true;
328                     args.pub = args.pub ? 't' : 'f';
329                     // close the dialog after edit has completed
330                     bucketSvc.editBucket(args).then(
331                         function() { $uibModalInstance.close() });
332                 }
333                 $scope.cancel = function () { $uibModalInstance.dismiss() }
334             }]
335         })
336     }
337
338     // opens the delete confirmation and deletes the current
339     // bucket if the user confirms.
340     $scope.openDeleteBucketDialog = function() {
341         $uibModal.open({
342             templateUrl: './cat/bucket/share/t_bucket_delete',
343             backdrop: 'static',
344             controller : 
345                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
346                 $scope.bucket = function() { return bucketSvc.currentBucket }
347                 $scope.ok = function() { $uibModalInstance.close() }
348                 $scope.cancel = function() { $uibModalInstance.dismiss() }
349             }]
350         }).result.then(function () {
351             bucketSvc.deleteBucket(bucketSvc.currentBucket.id())
352             .then(function() {
353                 bucketSvc.allBuckets = [];
354                 $location.path('/cat/bucket/copy/view');
355             });
356         });
357     }
358
359     // retrieves the requested bucket by ID
360     $scope.openSharedBucketDialog = function() {
361         $uibModal.open({
362             templateUrl: './cat/bucket/share/t_load_shared',
363             backdrop: 'static',
364             controller :
365                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
366                 $scope.focusMe = true;
367                 $scope.ok = function(args) {
368                     if (args && args.id) {
369                         $uibModalInstance.close(args.id)
370                     }
371                 }
372                 $scope.cancel = function() { $uibModalInstance.dismiss() }
373             }]
374         }).result.then(function(id) {
375             // RecordBucketCtrl $scope is not inherited by the
376             // modal, so we need to call loadBucket from the
377             // promise resolver.
378             $scope.loadBucket(id);
379         });
380     }
381
382 }])
383
384 .controller('PendingCtrl',
385        ['$scope','$routeParams','bucketSvc','egGridDataProvider', 'egCore',
386 function($scope,  $routeParams,  bucketSvc , egGridDataProvider,   egCore) {
387     $scope.setTab('pending');
388
389     $scope.context = {
390         copyNotFound : false,
391         selectPendingBC : true
392     };
393
394     var query;
395     $scope.gridControls = {
396         setQuery : function(q) {
397             if (bucketSvc.pendingList.length)
398                 return {id : bucketSvc.pendingList};
399             else
400             return null;
401         },
402         allItemsRetrieved : function() {
403             $scope.context.selectPendingBC = true;
404         }
405     }
406
407     $scope.handle_barcode_completion = function(barcode) {
408         return egCore.net.request(
409             'open-ils.actor',
410             'open-ils.actor.get_barcodes',
411             egCore.auth.token(), egCore.auth.user().ws_ou(), 
412             'asset', barcode)
413
414         .then(function(resp) {
415             // TODO: handle event during barcode lookup
416             if (evt = egCore.evt.parse(resp)) {
417                 console.error(evt.toString());
418                 return $q.reject();
419             }
420
421             // no matching barcodes: return the barcode as entered
422             // by the user (so that, e.g., checkout can fall back to
423             // precat/noncat handling)
424             if (!resp || !resp[0]) {
425                 return barcode;
426             }
427
428             // exactly one matching barcode: return it
429             if (resp.length == 1) {
430                 return resp[0].barcode;
431             }
432
433             // multiple matching barcodes: let the user pick one 
434             console.debug('multiple matching barcodes');
435             var matches = [];
436             var promises = [];
437             var final_barcode;
438             angular.forEach(resp, function(cp) {
439                 promises.push(
440                     egCore.net.request(
441                         'open-ils.circ',
442                         'open-ils.circ.copy_details.retrieve',
443                         egCore.auth.token(), cp.id
444                     ).then(function(r) {
445                         matches.push({
446                             barcode: r.copy.barcode(),
447                             title: r.mvr.title(),
448                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
449                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
450                         });
451                     })
452                 );
453             });
454             return $q.all(promises)
455             .then(function() {
456                 return $uibModal.open({
457                     templateUrl: './circ/share/t_barcode_choice_dialog',
458                     controller:
459                         ['$scope', '$uibModalInstance',
460                         function($scope, $uibModalInstance) {
461                         $scope.matches = matches;
462                         $scope.ok = function(barcode) {
463                             $uibModalInstance.close();
464                             final_barcode = barcode;
465                         }
466                         $scope.cancel = function() {$uibModalInstance.dismiss()}
467                     }],
468                 }).result.then(function() { return final_barcode });
469             })
470         });
471     }
472
473     $scope.search = function() {
474         bucketSvc.barcodeRecords = [];
475         $scope.context.itemNotFound = false;
476
477         // clear selection so re-selecting can have an effect
478         $scope.context.selectPendingBC = false;
479
480         return $scope.handle_barcode_completion(bucketSvc.barcodeString)
481         .then(function(actual_barcode) {
482             egCore.pcrud.search(
483                 'acp',
484                 {barcode : actual_barcode, deleted : 'f'},
485                 {}
486             ).then(function(copy) {
487                 if (copy) {
488                     bucketSvc.pendingList.push(copy.id());
489                     $scope.gridControls.setQuery({id : bucketSvc.pendingList});
490                     bucketSvc.barcodeString = ''; // clear form on valid copy
491                 } else {
492                     $scope.context.itemNotFound = true;
493                     $scope.context.selectPendingBC = true;
494                 }
495             });
496         });
497     }
498
499     $scope.resetPendingList = function() {
500         bucketSvc.pendingList = [];
501         $scope.gridControls.setQuery({});
502     }
503     
504     if ($routeParams.id && 
505         (!bucketSvc.currentBucket || 
506             bucketSvc.currentBucket.id() != $routeParams.id)) {
507         // user has accessed this page cold with a bucket ID.
508         // fetch the bucket for display, then set the totalCount
509         // (also for display), but avoid fully fetching the bucket,
510         // since it's premature, in this UI.
511         bucketSvc.fetchBucket($routeParams.id);
512     }
513     $scope.gridControls.setQuery();
514 }])
515
516 .controller('ViewCtrl',
517        ['$scope','$q','$routeParams','$timeout','$window','$uibModal','bucketSvc','egCore','egUser',
518         'egConfirmDialog',
519 function($scope,  $q , $routeParams , $timeout , $window , $uibModal , bucketSvc , egCore , egUser ,
520          egConfirmDialog) {
521
522     $scope.setTab('view');
523     $scope.bucketId = $routeParams.id;
524
525     var query;
526     $scope.gridControls = {
527         setQuery : function(q) {
528             if (q) query = q;
529             return query;
530         }
531     };
532
533     function drawBucket() {
534         return bucketSvc.fetchBucket($scope.bucketId).then(
535             function(bucket) {
536                 var ids = bucket.items().map(
537                     function(i){return i.target_copy()}
538                 );
539                 if (ids.length) {
540                     $scope.gridControls.setQuery({id : ids});
541                 } else {
542                     $scope.gridControls.setQuery({});
543                 }
544             }
545         );
546     }
547
548     $scope.detachCopies = function(copies) {
549         var promises = [];
550         angular.forEach(copies, function(rec) {
551             var item = bucketSvc.currentBucket.items().filter(
552                 function(i) {
553                     return (i.target_copy() == rec.id)
554                 }
555             );
556             if (item.length)
557                 promises.push(bucketSvc.detachCopy(item[0].id()));
558         });
559
560         bucketSvc.bucketNeedsRefresh = true;
561         return $q.all(promises).then(drawBucket);
562     }
563
564     $scope.spawnHoldingsEdit = function (copies) {
565         var cp_list = []
566         angular.forEach($scope.gridControls.selectedItems(), function (i) {
567             cp_list.push(i.id);
568         })
569
570         egCore.net.request(
571             'open-ils.actor',
572             'open-ils.actor.anon_cache.set_value',
573             null, 'edit-these-copies', {
574                 record_id: 0, // false-y value for record_id disables record summary
575                 copies: cp_list,
576                 hide_vols : true,
577                 hide_copies : false
578             }
579         ).then(function(key) {
580             if (key) {
581                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
582                 $timeout(function() { $window.open(url, '_blank') });
583             } else {
584                 alert('Could not create anonymous cache key!');
585             }
586         });
587     }
588
589     $scope.print_labels = function() {
590         var cp_list = []
591         angular.forEach($scope.gridControls.selectedItems(), function (i) {
592             cp_list.push(i.id);
593         })
594
595         egCore.net.request(
596             'open-ils.actor',
597             'open-ils.actor.anon_cache.set_value',
598             null, 'print-labels-these-copies', {
599                 copies : cp_list
600             }
601         ).then(function(key) {
602             if (key) {
603                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
604                 $timeout(function() { $window.open(url, '_blank') });
605             } else {
606                 alert('Could not create anonymous cache key!');
607             }
608         });
609     }
610
611     $scope.requestItems = function() {
612         var copy_list = $scope.gridControls.selectedItems().map(
613             function (i) {
614                 i.id;
615             }
616         );
617
618         if (copy_list.length == 0) return;
619
620         return $uibModal.open({
621             templateUrl: './cat/catalog/t_request_items',
622             backdrop: 'static',
623             animation: true,
624             controller:
625                    ['$scope','$uibModalInstance',
626             function($scope , $uibModalInstance) {
627                 $scope.user = null;
628                 $scope.first_user_fetch = true;
629
630                 $scope.hold_data = {
631                     hold_type : 'C',
632                     copy_list : copy_list,
633                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
634                     user      : egCore.auth.user().id()
635                 };
636
637                 egUser.get( $scope.hold_data.user ).then(function(u) {
638                     $scope.user = u;
639                     $scope.barcode = u.card().barcode();
640                     $scope.user_name = egUser.format_name(u);
641                     $scope.hold_data.user = u.id();
642                 });
643
644                 $scope.user_name = '';
645                 $scope.barcode = '';
646                 $scope.$watch('barcode', function (n) {
647                     if (!$scope.first_user_fetch) {
648                         egUser.getByBarcode(n).then(function(u) {
649                             $scope.user = u;
650                             $scope.user_name = egUser.format_name(u);
651                             $scope.hold_data.user = u.id();
652                         }, function() {
653                             $scope.user = null;
654                             $scope.user_name = '';
655                             delete $scope.hold_data.user;
656                         });
657                     }
658                     $scope.first_user_fetch = false;
659                 });
660
661                 $scope.ok = function(h) {
662                     var args = {
663                         patronid  : h.user,
664                         hold_type : h.hold_type,
665                         pickup_lib: h.pickup_lib.id(),
666                         depth     : 0
667                     };
668
669                     egCore.net.request(
670                         'open-ils.circ',
671                         'open-ils.circ.holds.test_and_create.batch.override',
672                         egCore.auth.token(), args, h.copy_list
673                     );
674
675                     $uibModalInstance.close();
676                 }
677
678                 $scope.cancel = function($event) {
679                     $uibModalInstance.dismiss();
680                     $event.preventDefault();
681                 }
682             }]
683         });
684     }
685
686     $scope.deleteCopiesFromCatalog = function(copies) {
687         egConfirmDialog.open(
688             egCore.strings.CONFIRM_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG,
689             '', {}
690         ).result.then(function() {
691             var fleshed_copies = [];
692             var promises = [];
693             angular.forEach(copies, function(i) {
694                 promises.push(
695                     egCore.net.request(
696                         'open-ils.search',
697                         'open-ils.search.asset.copy.fleshed2.retrieve',
698                         i.id
699                     ).then(function(copy) {
700                         copy.ischanged(1);
701                         copy.isdeleted(1);
702                         fleshed_copies.push(copy);
703                     })
704                 );
705             });
706             $q.all(promises).then(function() {
707                 egCore.net.request(
708                     'open-ils.cat',
709                     'open-ils.cat.asset.copy.fleshed.batch.update',
710                     egCore.auth.token(), fleshed_copies, true
711                 ).then(function(resp) {
712                     var evt = egCore.evt.parse(resp);
713                     if (evt) {
714                         egConfirmDialog.open(
715                             egCore.strings.OVERRIDE_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG_TITLE,
716                             egCore.strings.OVERRIDE_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG_BODY,
717                             {'evt_desc': evt.desc}
718                         ).result.then(function() {
719                             egCore.net.request(
720                                 'open-ils.cat',
721                                 'open-ils.cat.asset.copy.fleshed.batch.update.override',
722                                 egCore.auth.token(), fleshed_copies, true,
723                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
724                             ).then(function(resp) {
725                                 bucketSvc.bucketNeedsRefresh = true;
726                                 drawBucket();
727                             });
728                         });
729                     }
730                     bucketSvc.bucketNeedsRefresh = true;
731                     drawBucket();
732                 });
733             });
734         });
735     }
736
737     $scope.transferCopies = function(copies) {
738         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
739         var copy_ids = copies.map(
740             function(curr,idx,arr) {
741                 return curr.id;
742             }
743         );
744         if (xfer_target) {
745             egCore.net.request(
746                 'open-ils.cat',
747                 'open-ils.cat.transfer_copies_to_volume',
748                 egCore.auth.token(),
749                 xfer_target,
750                 copy_ids
751             ).then(
752                 function(resp) { // oncomplete
753                     var evt = egCore.evt.parse(resp);
754                     if (evt) {
755                         egConfirmDialog.open(
756                             egCore.strings.OVERRIDE_TRANSFER_COPY_BUCKET_ITEMS_TO_MARKED_VOLUME_TITLE,
757                             egCore.strings.OVERRIDE_TRANSFER_COPY_BUCKET_ITEMS_TO_MARKED_VOLUME_BODY,
758                             {'evt_desc': evt.desc}
759                         ).result.then(function() {
760                             egCore.net.request(
761                                 'open-ils.cat',
762                                 'open-ils.cat.transfer_copies_to_volume.override',
763                                 egCore.auth.token(),
764                                 xfer_target,
765                                 copy_ids,
766                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
767                             ).then(function(resp) {
768                                 bucketSvc.bucketNeedsRefresh = true;
769                                 drawBucket();
770                             });
771                         });
772                     } else {
773                         bucketSvc.bucketNeedsRefresh = true;
774                         drawBucket();
775                     }
776                 },
777                 null, // onerror
778                 null // onprogress
779             )
780         }
781     }
782
783     $scope.applyTags = function(copies) {
784         return $uibModal.open({
785             templateUrl: './cat/bucket/copy/t_apply_tags',
786             backdrop: 'static',
787             animation: true,
788             controller:
789                    ['$scope','$uibModalInstance',
790             function($scope , $uibModalInstance) {
791
792                 $scope.tag_map = [];
793
794                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
795                     $scope.tag_types = list;
796                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
797                 });
798
799                 $scope.getTags = function(val) {
800                     return egCore.pcrud.search('acpt',
801                         {
802                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
803                             label : { 'startwith' : {
804                                         transform: 'evergreen.lowercase',
805                                         value : [ 'evergreen.lowercase', val ]
806                                     }},
807                             tag_type : $scope.tag_type
808                         },
809                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
810                     ).then(function(list) {
811                         return list.map(function(item) {
812                             return item.label();
813                         });
814                     });
815                 }
816
817                 $scope.addTag = function() {
818                     var tagLabel = $scope.selectedLabel;
819                     // clear the typeahead
820                     $scope.selectedLabel = "";
821
822                     egCore.pcrud.search('acpt',
823                         {
824                             owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
825                             label : tagLabel,
826                             tag_type : $scope.tag_type
827                         },
828                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
829                     ).then(function(list) {
830                         if (list.length > 0) {
831                             var newMap = new egCore.idl.acptcm();
832                             newMap.isnew(1);
833                             newMap.tag(egCore.idl.Clone(list[0]));
834                             $scope.tag_map.push(newMap);
835                         }
836                     });
837                 }
838
839                 $scope.ok = function() {
840                     var promises = [];
841                     angular.forEach($scope.tag_map, function(map) {
842                         if (map.isdeleted()) return;
843                         angular.forEach(copies, function (cp) {
844                             var m = new egCore.idl.acptcm();
845                             m.isnew(1);
846                             m.copy(cp.id);
847                             m.tag(map.tag().id());
848                             promises.push(egCore.pcrud.create(m));
849                         });
850                     });
851                     return $q.all(promises).then(function(){$uibModalInstance.close()});
852                 }
853
854                 $scope.cancel = function($event) {
855                     $uibModalInstance.dismiss();
856                     $event.preventDefault();
857                 }
858             }]
859         });
860     }
861
862     // fetch the bucket;  on error show the not-allowed message
863     if ($scope.bucketId) 
864         drawBucket()['catch'](function() { $scope.forbidden = true });
865 }])