3208a42303cbcbe75f992de6dd3e09694b4bec7a
[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     return service;
219 }])
220
221 /**
222  * Top-level controller.  
223  * Hosts functions needed by all controllers.
224  */
225 .controller('CopyBucketCtrl',
226        ['$scope','$location','$q','$timeout','$uibModal',
227         '$window','egCore','bucketSvc',
228 function($scope,  $location,  $q,  $timeout,  $uibModal,  
229          $window,  egCore,  bucketSvc) {
230
231     $scope.bucketSvc = bucketSvc;
232     $scope.bucket = function() { return bucketSvc.currentBucket }
233
234     // tabs: search, pending, view
235     $scope.setTab = function(tab) { 
236         $scope.tab = tab;
237
238         // for bucket selector; must be called after route resolve
239         bucketSvc.fetchUserBuckets(); 
240     };
241
242     $scope.loadBucketFromMenu = function(item, bucket) {
243         if (bucket) return $scope.loadBucket(bucket.id());
244     }
245
246     $scope.loadBucket = function(id) {
247         $location.path(
248             '/cat/bucket/copy/' + 
249                 $scope.tab + '/' + encodeURIComponent(id));
250     }
251
252     $scope.addToBucket = function(recs) {
253         if (recs.length == 0) return;
254         bucketSvc.bucketNeedsRefresh = true;
255
256         angular.forEach(recs,
257             function(rec) {
258                 var item = new egCore.idl.ccbi();
259                 item.bucket(bucketSvc.currentBucket.id());
260                 item.target_copy(rec.id);
261                 egCore.net.request(
262                     'open-ils.actor',
263                     'open-ils.actor.container.item.create', 
264                     egCore.auth.token(), 'copy', item
265                 ).then(function(resp) {
266
267                     // HACK: add the IDs of the added items so that the size
268                     // of the view list will grow (and update any UI looking at
269                     // the list size).  The data stored is inconsistent, but since
270                     // we are forcing a bucket refresh on the next rendering of 
271                     // the view pane, the list will be repaired.
272                     bucketSvc.currentBucket.items().push(resp);
273                 });
274             }
275         );
276     }
277
278     $scope.openCreateBucketDialog = function() {
279         $uibModal.open({
280             templateUrl: './cat/bucket/share/t_bucket_create',
281             backdrop: 'static',
282             controller: 
283                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
284                 $scope.focusMe = true;
285                 $scope.ok = function(args) { $uibModalInstance.close(args) }
286                 $scope.cancel = function () { $uibModalInstance.dismiss() }
287             }]
288         }).result.then(function (args) {
289             if (!args || !args.name) return;
290             bucketSvc.createBucket(args.name, args.desc).then(
291                 function(id) {
292                     if (!id) return;
293                     bucketSvc.viewList = [];
294                     bucketSvc.allBuckets = []; // reset
295                     bucketSvc.currentBucket = null;
296                     $location.path(
297                         '/cat/bucket/copy/' + $scope.tab + '/' + id);
298                 }
299             );
300         });
301     }
302
303     $scope.openEditBucketDialog = function() {
304         $uibModal.open({
305             templateUrl: './cat/bucket/share/t_bucket_edit',
306             backdrop: 'static',
307             controller: 
308                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
309                 $scope.focusMe = true;
310                 $scope.args = {
311                     name : bucketSvc.currentBucket.name(),
312                     desc : bucketSvc.currentBucket.description(),
313                     pub : bucketSvc.currentBucket.pub() == 't'
314                 };
315                 $scope.ok = function(args) { 
316                     if (!args) return;
317                     $scope.actionPending = true;
318                     args.pub = args.pub ? 't' : 'f';
319                     // close the dialog after edit has completed
320                     bucketSvc.editBucket(args).then(
321                         function() { $uibModalInstance.close() });
322                 }
323                 $scope.cancel = function () { $uibModalInstance.dismiss() }
324             }]
325         })
326     }
327
328     // opens the delete confirmation and deletes the current
329     // bucket if the user confirms.
330     $scope.openDeleteBucketDialog = function() {
331         $uibModal.open({
332             templateUrl: './cat/bucket/share/t_bucket_delete',
333             backdrop: 'static',
334             controller : 
335                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
336                 $scope.bucket = function() { return bucketSvc.currentBucket }
337                 $scope.ok = function() { $uibModalInstance.close() }
338                 $scope.cancel = function() { $uibModalInstance.dismiss() }
339             }]
340         }).result.then(function () {
341             bucketSvc.deleteBucket(bucketSvc.currentBucket.id())
342             .then(function() {
343                 bucketSvc.allBuckets = [];
344                 $location.path('/cat/bucket/copy/view');
345             });
346         });
347     }
348
349     // retrieves the requested bucket by ID
350     $scope.openSharedBucketDialog = function() {
351         $uibModal.open({
352             templateUrl: './cat/bucket/share/t_load_shared',
353             backdrop: 'static',
354             controller :
355                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
356                 $scope.focusMe = true;
357                 $scope.ok = function(args) {
358                     if (args && args.id) {
359                         $uibModalInstance.close(args.id)
360                     }
361                 }
362                 $scope.cancel = function() { $uibModalInstance.dismiss() }
363             }]
364         }).result.then(function(id) {
365             // RecordBucketCtrl $scope is not inherited by the
366             // modal, so we need to call loadBucket from the
367             // promise resolver.
368             $scope.loadBucket(id);
369         });
370     }
371
372 }])
373
374 .controller('PendingCtrl',
375        ['$scope','$routeParams','bucketSvc','egGridDataProvider', 'egCore',
376 function($scope,  $routeParams,  bucketSvc , egGridDataProvider,   egCore) {
377     $scope.setTab('pending');
378
379     $scope.context = {
380         copyNotFound : false,
381         selectPendingBC : true
382     };
383
384     var query;
385     $scope.gridControls = {
386         setQuery : function(q) {
387             if (bucketSvc.pendingList.length)
388                 return {id : bucketSvc.pendingList};
389             else
390             return null;
391         },
392         allItemsRetrieved : function() {
393             $scope.context.selectPendingBC = true;
394         }
395     }
396
397     $scope.handle_barcode_completion = function(barcode) {
398         return egCore.net.request(
399             'open-ils.actor',
400             'open-ils.actor.get_barcodes',
401             egCore.auth.token(), egCore.auth.user().ws_ou(), 
402             'asset', barcode)
403
404         .then(function(resp) {
405             // TODO: handle event during barcode lookup
406             if (evt = egCore.evt.parse(resp)) {
407                 console.error(evt.toString());
408                 return $q.reject();
409             }
410
411             // no matching barcodes: return the barcode as entered
412             // by the user (so that, e.g., checkout can fall back to
413             // precat/noncat handling)
414             if (!resp || !resp[0]) {
415                 return barcode;
416             }
417
418             // exactly one matching barcode: return it
419             if (resp.length == 1) {
420                 return resp[0].barcode;
421             }
422
423             // multiple matching barcodes: let the user pick one 
424             console.debug('multiple matching barcodes');
425             var matches = [];
426             var promises = [];
427             var final_barcode;
428             angular.forEach(resp, function(cp) {
429                 promises.push(
430                     egCore.net.request(
431                         'open-ils.circ',
432                         'open-ils.circ.copy_details.retrieve',
433                         egCore.auth.token(), cp.id
434                     ).then(function(r) {
435                         matches.push({
436                             barcode: r.copy.barcode(),
437                             title: r.mvr.title(),
438                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
439                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
440                         });
441                     })
442                 );
443             });
444             return $q.all(promises)
445             .then(function() {
446                 return $uibModal.open({
447                     templateUrl: './circ/share/t_barcode_choice_dialog',
448                     controller:
449                         ['$scope', '$uibModalInstance',
450                         function($scope, $uibModalInstance) {
451                         $scope.matches = matches;
452                         $scope.ok = function(barcode) {
453                             $uibModalInstance.close();
454                             final_barcode = barcode;
455                         }
456                         $scope.cancel = function() {$uibModalInstance.dismiss()}
457                     }],
458                 }).result.then(function() { return final_barcode });
459             })
460         });
461     }
462
463     $scope.search = function() {
464         bucketSvc.barcodeRecords = [];
465         $scope.context.itemNotFound = false;
466
467         // clear selection so re-selecting can have an effect
468         $scope.context.selectPendingBC = false;
469
470         return $scope.handle_barcode_completion(bucketSvc.barcodeString)
471         .then(function(actual_barcode) {
472             egCore.pcrud.search(
473                 'acp',
474                 {barcode : actual_barcode, deleted : 'f'},
475                 {}
476             ).then(function(copy) {
477                 if (copy) {
478                     bucketSvc.pendingList.push(copy.id());
479                     $scope.gridControls.setQuery({id : bucketSvc.pendingList});
480                     bucketSvc.barcodeString = ''; // clear form on valid copy
481                 } else {
482                     $scope.context.itemNotFound = true;
483                     $scope.context.selectPendingBC = true;
484                 }
485             });
486         });
487     }
488
489     $scope.resetPendingList = function() {
490         bucketSvc.pendingList = [];
491         $scope.gridControls.setQuery({});
492     }
493     
494     if ($routeParams.id && 
495         (!bucketSvc.currentBucket || 
496             bucketSvc.currentBucket.id() != $routeParams.id)) {
497         // user has accessed this page cold with a bucket ID.
498         // fetch the bucket for display, then set the totalCount
499         // (also for display), but avoid fully fetching the bucket,
500         // since it's premature, in this UI.
501         bucketSvc.fetchBucket($routeParams.id);
502     }
503     $scope.gridControls.setQuery();
504 }])
505
506 .controller('ViewCtrl',
507        ['$scope','$q','$routeParams','$timeout','$window','$uibModal','bucketSvc','egCore','egUser',
508         'egConfirmDialog',
509 function($scope,  $q , $routeParams , $timeout , $window , $uibModal , bucketSvc , egCore , egUser ,
510          egConfirmDialog) {
511
512     $scope.setTab('view');
513     $scope.bucketId = $routeParams.id;
514
515     var query;
516     $scope.gridControls = {
517         setQuery : function(q) {
518             if (q) query = q;
519             return query;
520         }
521     };
522
523     function drawBucket() {
524         return bucketSvc.fetchBucket($scope.bucketId).then(
525             function(bucket) {
526                 var ids = bucket.items().map(
527                     function(i){return i.target_copy()}
528                 );
529                 if (ids.length) {
530                     $scope.gridControls.setQuery({id : ids});
531                 } else {
532                     $scope.gridControls.setQuery({});
533                 }
534             }
535         );
536     }
537
538     $scope.detachCopies = function(copies) {
539         var promises = [];
540         angular.forEach(copies, function(rec) {
541             var item = bucketSvc.currentBucket.items().filter(
542                 function(i) {
543                     return (i.target_copy() == rec.id)
544                 }
545             );
546             if (item.length)
547                 promises.push(bucketSvc.detachCopy(item[0].id()));
548         });
549
550         bucketSvc.bucketNeedsRefresh = true;
551         return $q.all(promises).then(drawBucket);
552     }
553
554     $scope.spawnHoldingsEdit = function (copies) {
555         var cp_list = []
556         angular.forEach($scope.gridControls.selectedItems(), function (i) {
557             cp_list.push(i.id);
558         })
559
560         egCore.net.request(
561             'open-ils.actor',
562             'open-ils.actor.anon_cache.set_value',
563             null, 'edit-these-copies', {
564                 record_id: 0, // false-y value for record_id disables record summary
565                 copies: cp_list,
566                 hide_vols : true,
567                 hide_copies : false
568             }
569         ).then(function(key) {
570             if (key) {
571                 var url = egCore.env.basePath + 'cat/volcopy/' + key;
572                 $timeout(function() { $window.open(url, '_blank') });
573             } else {
574                 alert('Could not create anonymous cache key!');
575             }
576         });
577     }
578
579     $scope.print_labels = function() {
580         var cp_list = []
581         angular.forEach($scope.gridControls.selectedItems(), function (i) {
582             cp_list.push(i.id);
583         })
584
585         egCore.net.request(
586             'open-ils.actor',
587             'open-ils.actor.anon_cache.set_value',
588             null, 'print-labels-these-copies', {
589                 copies : cp_list
590             }
591         ).then(function(key) {
592             if (key) {
593                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
594                 $timeout(function() { $window.open(url, '_blank') });
595             } else {
596                 alert('Could not create anonymous cache key!');
597             }
598         });
599     }
600
601     $scope.requestItems = function() {
602         var copy_list = $scope.gridControls.selectedItems().map(
603             function (i) {
604                 i.id;
605             }
606         );
607
608         if (copy_list.length == 0) return;
609
610         return $uibModal.open({
611             templateUrl: './cat/catalog/t_request_items',
612             backdrop: 'static',
613             animation: true,
614             controller:
615                    ['$scope','$uibModalInstance',
616             function($scope , $uibModalInstance) {
617                 $scope.user = null;
618                 $scope.first_user_fetch = true;
619
620                 $scope.hold_data = {
621                     hold_type : 'C',
622                     copy_list : copy_list,
623                     pickup_lib: egCore.org.get(egCore.auth.user().ws_ou()),
624                     user      : egCore.auth.user().id()
625                 };
626
627                 egUser.get( $scope.hold_data.user ).then(function(u) {
628                     $scope.user = u;
629                     $scope.barcode = u.card().barcode();
630                     $scope.user_name = egUser.format_name(u);
631                     $scope.hold_data.user = u.id();
632                 });
633
634                 $scope.user_name = '';
635                 $scope.barcode = '';
636                 $scope.$watch('barcode', function (n) {
637                     if (!$scope.first_user_fetch) {
638                         egUser.getByBarcode(n).then(function(u) {
639                             $scope.user = u;
640                             $scope.user_name = egUser.format_name(u);
641                             $scope.hold_data.user = u.id();
642                         }, function() {
643                             $scope.user = null;
644                             $scope.user_name = '';
645                             delete $scope.hold_data.user;
646                         });
647                     }
648                     $scope.first_user_fetch = false;
649                 });
650
651                 $scope.ok = function(h) {
652                     var args = {
653                         patronid  : h.user,
654                         hold_type : h.hold_type,
655                         pickup_lib: h.pickup_lib.id(),
656                         depth     : 0
657                     };
658
659                     egCore.net.request(
660                         'open-ils.circ',
661                         'open-ils.circ.holds.test_and_create.batch.override',
662                         egCore.auth.token(), args, h.copy_list
663                     );
664
665                     $uibModalInstance.close();
666                 }
667
668                 $scope.cancel = function($event) {
669                     $uibModalInstance.dismiss();
670                     $event.preventDefault();
671                 }
672             }]
673         });
674     }
675
676     $scope.deleteCopiesFromCatalog = function(copies) {
677         egConfirmDialog.open(
678             egCore.strings.CONFIRM_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG,
679             '', {}
680         ).result.then(function() {
681             var fleshed_copies = [];
682             var promises = [];
683             angular.forEach(copies, function(i) {
684                 promises.push(
685                     egCore.net.request(
686                         'open-ils.search',
687                         'open-ils.search.asset.copy.fleshed2.retrieve',
688                         i.id
689                     ).then(function(copy) {
690                         copy.ischanged(1);
691                         copy.isdeleted(1);
692                         fleshed_copies.push(copy);
693                     })
694                 );
695             });
696             $q.all(promises).then(function() {
697                 egCore.net.request(
698                     'open-ils.cat',
699                     'open-ils.cat.asset.copy.fleshed.batch.update',
700                     egCore.auth.token(), fleshed_copies, true
701                 ).then(function(resp) {
702                     var evt = egCore.evt.parse(resp);
703                     if (evt) {
704                         egConfirmDialog.open(
705                             egCore.strings.OVERRIDE_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG_TITLE,
706                             egCore.strings.OVERRIDE_DELETE_COPY_BUCKET_ITEMS_FROM_CATALOG_BODY,
707                             {'evt_desc': evt.desc}
708                         ).result.then(function() {
709                             egCore.net.request(
710                                 'open-ils.cat',
711                                 'open-ils.cat.asset.copy.fleshed.batch.update.override',
712                                 egCore.auth.token(), fleshed_copies, true,
713                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
714                             ).then(function(resp) {
715                                 bucketSvc.bucketNeedsRefresh = true;
716                                 drawBucket();
717                             });
718                         });
719                     }
720                     bucketSvc.bucketNeedsRefresh = true;
721                     drawBucket();
722                 });
723             });
724         });
725     }
726
727     $scope.transferCopies = function(copies) {
728         var xfer_target = egCore.hatch.getLocalItem('eg.cat.transfer_target_vol');
729         var copy_ids = copies.map(
730             function(curr,idx,arr) {
731                 return curr.id;
732             }
733         );
734         if (xfer_target) {
735             egCore.net.request(
736                 'open-ils.cat',
737                 'open-ils.cat.transfer_copies_to_volume',
738                 egCore.auth.token(),
739                 xfer_target,
740                 copy_ids
741             ).then(
742                 function(resp) { // oncomplete
743                     var evt = egCore.evt.parse(resp);
744                     if (evt) {
745                         egConfirmDialog.open(
746                             egCore.strings.OVERRIDE_TRANSFER_COPY_BUCKET_ITEMS_TO_MARKED_VOLUME_TITLE,
747                             egCore.strings.OVERRIDE_TRANSFER_COPY_BUCKET_ITEMS_TO_MARKED_VOLUME_BODY,
748                             {'evt_desc': evt.desc}
749                         ).result.then(function() {
750                             egCore.net.request(
751                                 'open-ils.cat',
752                                 'open-ils.cat.transfer_copies_to_volume.override',
753                                 egCore.auth.token(),
754                                 xfer_target,
755                                 copy_ids,
756                                 { events: ['TITLE_LAST_COPY', 'COPY_DELETE_WARNING'] }
757                             ).then(function(resp) {
758                                 bucketSvc.bucketNeedsRefresh = true;
759                                 drawBucket();
760                             });
761                         });
762                     } else {
763                         bucketSvc.bucketNeedsRefresh = true;
764                         drawBucket();
765                     }
766                 },
767                 null, // onerror
768                 null // onprogress
769             )
770         }
771     }
772
773     $scope.applyTags = function(copies) {
774         return $uibModal.open({
775             templateUrl: './cat/bucket/copy/t_apply_tags',
776             backdrop: 'static',
777             animation: true,
778             controller:
779                    ['$scope','$uibModalInstance',
780             function($scope , $uibModalInstance) {
781
782                 $scope.tag_map = [];
783
784                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
785                     $scope.tag_types = list;
786                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
787                 });
788
789                 $scope.getTags = function(val) {
790                     return egCore.pcrud.search('acpt',
791                         {
792                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
793                             label : { 'startwith' : {
794                                         transform: 'evergreen.lowercase',
795                                         value : [ 'evergreen.lowercase', val ]
796                                     }},
797                             tag_type : $scope.tag_type
798                         },
799                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
800                     ).then(function(list) {
801                         return list.map(function(item) {
802                             return item.label();
803                         });
804                     });
805                 }
806
807                 $scope.addTag = function() {
808                     var tagLabel = $scope.selectedLabel;
809                     // clear the typeahead
810                     $scope.selectedLabel = "";
811
812                     egCore.pcrud.search('acpt',
813                         {
814                             owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
815                             label : tagLabel,
816                             tag_type : $scope.tag_type
817                         },
818                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
819                     ).then(function(list) {
820                         if (list.length > 0) {
821                             var newMap = new egCore.idl.acptcm();
822                             newMap.isnew(1);
823                             newMap.tag(egCore.idl.Clone(list[0]));
824                             $scope.tag_map.push(newMap);
825                         }
826                     });
827                 }
828
829                 $scope.ok = function() {
830                     var promises = [];
831                     angular.forEach($scope.tag_map, function(map) {
832                         if (map.isdeleted()) return;
833                         angular.forEach(copies, function (cp) {
834                             var m = new egCore.idl.acptcm();
835                             m.isnew(1);
836                             m.copy(cp.id);
837                             m.tag(map.tag().id());
838                             promises.push(egCore.pcrud.create(m));
839                         });
840                     });
841                     return $q.all(promises).then(function(){$uibModalInstance.close()});
842                 }
843
844                 $scope.cancel = function($event) {
845                     $uibModalInstance.dismiss();
846                     $event.preventDefault();
847                 }
848             }]
849         });
850     }
851
852     // fetch the bucket;  on error show the not-allowed message
853     if ($scope.bucketId) 
854         drawBucket()['catch'](function() { $scope.forbidden = true });
855 }])