5923b401b26354e80f27409512cf33957569496e
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / volcopy / app.js
1 /**
2  * Vol/Copy Editor
3  */
4
5 angular.module('egVolCopy',
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
7
8 .filter('boolText', function(){
9     return function (v) {
10         return v == 't';
11     }
12 })
13
14 .config(['ngToastProvider', function(ngToastProvider) {
15   ngToastProvider.configure({
16     verticalPosition: 'bottom',
17     animation: 'fade'
18   });
19 }])
20
21 .config(function($routeProvider, $locationProvider, $compileProvider) {
22     $locationProvider.html5Mode(true);
23     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
24         
25     var resolver = {
26         delay : ['egStartup', function(egStartup) { return egStartup.go(); }]
27     };
28
29     $routeProvider.when('/cat/volcopy/edit_templates', {
30         templateUrl: './cat/volcopy/t_view',
31         controller: 'EditCtrl',
32         resolve : resolver
33     });
34
35     $routeProvider.when('/cat/volcopy/:dataKey', {
36         templateUrl: './cat/volcopy/t_view',
37         controller: 'EditCtrl',
38         resolve : resolver
39     });
40
41     $routeProvider.when('/cat/volcopy/:dataKey/:mode', {
42         templateUrl: './cat/volcopy/t_view',
43         controller: 'EditCtrl',
44         resolve : resolver
45     });
46 })
47
48 .factory('itemSvc', 
49        ['egCore','$q',
50 function(egCore , $q) {
51
52     var service = {
53         currently_generating : false,
54         auto_gen_barcode : false,
55         barcode_checkdigit : false,
56         new_cp_id : 0,
57         new_cn_id : 0,
58         tree : {}, // holds lib->cn->copy hash stack
59         copies : [] // raw copy list
60     };
61
62     service.nextBarcode = function(bc) {
63         service.currently_generating = true;
64         return egCore.net.request(
65             'open-ils.cat',
66             'open-ils.cat.item.barcode.autogen',
67             egCore.auth.token(),
68             bc, 1, { checkdigit: service.barcode_checkdigit }
69         ).then(function(resp) { // get_barcodes
70             var evt = egCore.evt.parse(resp);
71             if (!evt) return resp[0];
72             return '';
73         });
74     };
75
76     service.checkBarcode = function(bc) {
77         if (!service.barcode_checkdigit) return true;
78         if (bc != Number(bc)) return false;
79         bc = bc.toString();
80         // "16.00" == Number("16.00"), but the . is bad.
81         // Throw out any barcode that isn't just digits
82         if (bc.search(/\D/) != -1) return false;
83         var last_digit = bc.substr(bc.length-1);
84         var stripped_barcode = bc.substr(0,bc.length-1);
85         return service.barcodeCheckdigit(stripped_barcode).toString() == last_digit;
86     };
87
88     service.barcodeCheckdigit = function(bc) {
89         var reverse_barcode = bc.toString().split('').reverse();
90         var check_sum = 0; var multiplier = 2;
91         for (var i = 0; i < reverse_barcode.length; i++) {
92             var digit = reverse_barcode[i];
93             var product = digit * multiplier; product = product.toString();
94             var temp_sum = 0;
95             for (var j = 0; j < product.length; j++) {
96                 temp_sum += Number( product[j] );
97             }
98             check_sum += Number( temp_sum );
99             multiplier = ( multiplier == 2 ? 1 : 2 );
100         }
101         check_sum = check_sum.toString();
102         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
103         var check_digit = next_multiple_of_10 - Number(check_sum); if (check_digit == 10) check_digit = 0;
104         return check_digit;
105     };
106
107     // returns a promise resolved with the list of circ mods
108     service.get_classifications = function() {
109         if (egCore.env.acnc)
110             return $q.when(egCore.env.acnc.list);
111
112         return egCore.pcrud.retrieveAll('acnc', null, {atomic : true})
113         .then(function(list) {
114             egCore.env.absorbList(list, 'acnc');
115             return list;
116         });
117     };
118
119     service.get_prefixes = function(org) {
120         return egCore.pcrud.search('acnp',
121             {owning_lib : egCore.org.fullPath(org, true)},
122             {order_by : { acnp : 'label_sortkey' }}, {atomic : true}
123         );
124
125     };
126
127     service.get_statcats = function(orgs) {
128         return egCore.pcrud.search('asc',
129             {owner : orgs},
130             { flesh : 1,
131               flesh_fields : {
132                 asc : ['owner','entries']
133               }
134             },
135             { atomic : true }
136         );
137     };
138
139     service.get_copy_alert_types = function(orgs) {
140         return egCore.pcrud.search('ccat',
141             { active : 't' },
142             {},
143             { atomic : true }
144         );
145     };
146
147     service.get_copy_alerts = function(copy_id) {
148         return egCore.pcrud.search('aca', { copy : copy_id, ack_time : null },
149             { flesh : 1, flesh_fields : { aca : ['alert_type'] } },
150             { atomic : true }
151         );
152     };
153
154     service.get_locations_by_org = function(orgs) {
155         return egCore.pcrud.search('acpl',
156             {owning_lib : orgs, deleted : 'f'},
157             {
158                 flesh : 1,
159                 flesh_fields : {
160                     acpl : ['owning_lib']
161                 },
162                 order_by : { acpl : 'name' }
163             },
164             {atomic : true}
165         );
166     };
167
168     service.fetch_locations = function(locs) {
169         return egCore.pcrud.search('acpl',
170             {id : locs},
171             {
172                 flesh : 1,
173                 flesh_fields : {
174                     acpl : ['owning_lib']
175                 },
176                 order_by : { acpl : 'name' }
177             },
178             {atomic : true}
179         );
180     };
181
182     service.get_suffixes = function(org) {
183         return egCore.pcrud.search('acns',
184             {owning_lib : egCore.org.fullPath(org, true)},
185             {order_by : { acns : 'label_sortkey' }}, {atomic : true}
186         );
187
188     };
189
190     service.get_magic_statuses = function() {
191         /* TODO: make these more configurable per lp1616170 */
192         return $q.when([
193              1  /* Checked out */
194             ,3  /* Lost */
195             ,6  /* In transit */
196             ,8  /* On holds shelf */
197             ,16 /* Long overdue */
198             ,18 /* Canceled Transit */
199         ]);
200     }
201
202     service.get_statuses = function() {
203         if (egCore.env.ccs)
204             return $q.when(egCore.env.ccs.list);
205
206         return egCore.pcrud.retrieveAll('ccs', {order_by : { ccs : 'name' }}, {atomic : true}).then(
207             function(list) {
208                 egCore.env.absorbList(list, 'ccs');
209                 return list;
210             }
211         );
212
213     };
214
215     service.get_circ_mods = function() {
216         if (egCore.env.ccm)
217             return $q.when(egCore.env.ccm.list);
218
219         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
220             function(list) {
221                 egCore.env.absorbList(list, 'ccm');
222                 return list;
223             }
224         );
225
226     };
227
228     service.get_circ_types = function() {
229         if (egCore.env.citm)
230             return $q.when(egCore.env.citm.list);
231
232         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
233             function(list) {
234                 egCore.env.absorbList(list, 'citm');
235                 return list;
236             }
237         );
238
239     };
240
241     service.get_age_protects = function() {
242         if (egCore.env.crahp)
243             return $q.when(egCore.env.crahp.list);
244
245         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
246             function(list) {
247                 egCore.env.absorbList(list, 'crahp');
248                 return list;
249             }
250         );
251
252     };
253
254     service.get_floating_groups = function() {
255         if (egCore.env.cfg)
256             return $q.when(egCore.env.cfg.list);
257
258         return egCore.pcrud.retrieveAll('cfg', {}, {atomic : true}).then(
259             function(list) {
260                 egCore.env.absorbList(list, 'cfg');
261                 return list;
262             }
263         );
264
265     };
266
267     service.bmp_parts = {};
268     service.get_parts = function(rec) {
269         if (service.bmp_parts[rec])
270             return $q.when(service.bmp_parts[rec]);
271
272         return egCore.pcrud.search('bmp',
273             {record : rec, deleted : 'f'},
274             null, {atomic : true}
275         ).then(function(list) {
276             service.bmp_parts[rec] = list;
277             return list;
278         });
279
280     };
281
282     service.get_acp_templates = function() {
283         // Already downloaded for this user? Return local copy. Changing users or logging out causes another download
284         // so users always have their own templates, and any changes made on other machines appear as expected.
285         if (egCore.hatch.getSessionItem('cat.copy.templates.usr') == egCore.auth.user().id()) {
286             return egCore.hatch.getItem('cat.copy.templates').then(function(templ) {
287                 return templ;
288             });
289         } else {
290             // this can be disabled for debugging to force a re-download and translation of test templates
291             egCore.hatch.setSessionItem('cat.copy.templates.usr', egCore.auth.user().id());
292             return service.load_remote_acp_templates();
293         }
294
295     };
296
297     service.save_acp_templates = function(t) {
298         egCore.hatch.setItem('cat.copy.templates', t);
299         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
300             egCore.auth.token(), egCore.auth.user().id(), { "webstaff.cat.copy.templates": t });
301         // console.warn('Saved ' + JSON.stringify({"webstaff.cat.copy.templates": t}));
302     };
303
304     service.load_remote_acp_templates = function() {
305         // After the XUL Client is completely removed everything related
306         // to staff_client.copy_editor.templates and convert_xul_templates
307         // can be thrown away.
308         return egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative',
309             egCore.auth.token(), egCore.auth.user().id(),
310             ['webstaff.cat.copy.templates','staff_client.copy_editor.templates']).then(function(settings) {
311                 if (settings['webstaff.cat.copy.templates']) {
312                     egCore.hatch.setItem('cat.copy.templates', settings['webstaff.cat.copy.templates']);
313                     return settings['webstaff.cat.copy.templates'];
314                 } else {
315                     if (settings['staff_client.copy_editor.templates']) {
316                         var new_templ = service.convert_xul_templates(settings['staff_client.copy_editor.templates']);
317                         egCore.hatch.setItem('cat.copy.templates', new_templ);
318                         // console.warn('Saving: ' + JSON.stringify({'webstaff.cat.copy.templates' : new_templ}));
319                         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
320                             egCore.auth.token(), egCore.auth.user().id(), {'webstaff.cat.copy.templates' : new_templ});
321                         return new_templ;
322                     }
323                 }
324                 return {};
325         });
326     };
327
328     service.convert_xul_templates = function(xultempl) {
329         var conv_templ = {};
330         var templ_names = Object.keys(xultempl);
331         var name;
332         var xul_t;
333         var curr_templ;
334         var stat_cats;
335         var fields;
336         var curr_field;
337         var tmp_val;
338         var i, j;
339
340         if (templ_names) {
341             for (i=0; i < templ_names.length; i++) {
342                 name = templ_names[i];
343                 curr_templ = {};
344                 stat_cats = {};
345                 xul_t  = xultempl[name];
346                 fields = Object.keys(xul_t);
347
348                 if (fields.length > 0) {
349                     for (j=0; j < fields.length; j++) {
350                         curr_field = xul_t[fields[j]];
351                         var field_name = curr_field["field"];
352
353                         if ( field_name == null ) { continue; }
354                         if ( curr_field["value"] == "<HACK:KLUDGE:NULL>" ) { continue; }
355
356                         // floating changed from a boolean to an integer at one point;
357                         // take this opportunity to remove the boolean from any old templates
358                         if ( curr_field["type"] === "attribute" && field_name === "floating" ) {
359                             if ( curr_field["value"].match(/[tf]/) ) { continue; }
360                         }
361
362                         if ( curr_field["type"] === "stat_cat" ) {
363                             stat_cats[field_name] = parseInt(curr_field["value"]);
364                         } else {
365                             tmp_val = curr_field['value'];
366                             if ( tmp_val.toString().match(/^[-0-9.]+$/)) {
367                                 tmp_val = parseFloat(tmp_val);
368                             }
369
370                             if (field_name.match(/^batch_.*_menulist$/)) {
371                                 // special handling for volume fields
372                                 if (!("callnumber" in curr_templ)) curr_templ["callnumber"] = {};
373                                 if (field_name === "batch_class_menulist")  curr_templ["callnumber"]["classification"] = tmp_val;
374                                 if (field_name === "batch_prefix_menulist") curr_templ["callnumber"]["prefix"] = tmp_val;
375                                 if (field_name === "batch_suffix_menulist") curr_templ["callnumber"]["suffix"] = tmp_val;
376                             } else {
377                                 curr_templ[field_name] = tmp_val;
378                             }
379                         }
380                     }
381
382                     if ( (Object.keys(stat_cats)).length > 0 ) {
383                         curr_templ["statcats"] = stat_cats;
384                     }
385
386                     conv_templ[name] = curr_templ;
387                 }
388             }
389         }
390         return conv_templ;
391     };
392
393     service.flesh = {   
394         flesh : 3, 
395         flesh_fields : {
396             acp : ['call_number','parts','stat_cat_entries', 'notes', 'tags'],
397             acn : ['label_class','prefix','suffix'],
398             acptcm : ['tag']
399         }
400     }
401
402     service.addCopy = function (cp) {
403
404         if (!cp.parts()) cp.parts([]); // just in case...
405
406         service.get_copy_alerts(cp.id()).then(function(aca) {
407             cp.copy_alerts(aca);
408         });
409
410         var lib = cp.call_number().owning_lib();
411         var cn = cp.call_number().id();
412
413         if (!service.tree[lib]) service.tree[lib] = {};
414         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
415
416         service.tree[lib][cn].push(cp);
417         service.copies.push(cp);
418     }
419
420     service.checkDuplicateBarcode = function(bc, id) {
421         var final = false;
422         return egCore.pcrud.search('acp', { deleted : 'f', 'barcode' : bc, id : { '!=' : id } })
423             .then(
424                 function () { return final },
425                 function () { return final },
426                 function () { final = true; }
427             );
428     }
429
430     service.fetchIds = function(idList) {
431         service.tree = {}; // clear the tree on fetch
432         service.copies = []; // clear the copy list on fetch
433         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
434             function(copy) {
435                 service.addCopy(copy);
436             }
437         );
438     }
439
440     // create a new acp object with default values
441     // (both hard-coded and coming from OU settings)
442     service.generateNewCopy = function(callNumber, owningLib, isFastAdd, isNew) {
443         var cp = new egCore.idl.acp();
444         cp.id( --service.new_cp_id );
445         if (isNew) {
446             cp.isnew( true );
447         }
448         cp.circ_lib( owningLib );
449         cp.call_number( callNumber );
450         cp.deposit(0);
451         cp.price(0);
452         cp.deposit_amount(0);
453         cp.fine_level(2); // Normal
454         cp.loan_duration(2); // Normal
455         cp.location(1); // Stacks
456         cp.circulate('t');
457         cp.holdable('t');
458         cp.opac_visible('t');
459         cp.ref('f');
460         cp.mint_condition('t');
461         cp.empty_barcode = true;
462
463         var status_setting = isFastAdd ?
464             'cat.default_copy_status_fast' :
465             'cat.default_copy_status_normal';
466         egCore.org.settings(
467             [status_setting],
468             owningLib
469         ).then(function(set) {
470             var default_ccs = parseInt(set[status_setting]);
471             if (isNaN(default_ccs))
472                 default_ccs = (isFastAdd ? 0 : 5); // 0 is Available, 5 is In Process
473             cp.status(default_ccs);
474         });
475
476         return cp;
477     }
478
479     return service;
480 }])
481
482 .directive("egVolCopyEdit", function () {
483     return {
484         restrict: 'E',
485         replace: true,
486         template:
487             '<div class="row">'+
488                 '<div class="col-xs-5" ng-class="{'+"'has-error'"+':barcode_has_error}">'+
489                     '<input id="{{callNumber.id()}}_{{copy.id()}}"'+
490                     ' eg-enter="nextBarcode(copy.id())" class="form-control"'+
491                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"'+
492                     ' ng-focus="selectOnFocus($event)" autofocus/>'+
493                     '<div class="label label-danger" ng-if="duplicate_barcode">{{duplicate_barcode_string}}</div>'+
494                     '<div class="label label-danger" ng-if="empty_barcode">{{empty_barcode_string}}</div>'+
495                 '</div>'+
496                 '<div class="col-xs-3"><input class="form-control" type="number" min="1" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
497                 '<div class="col-xs-3"><eg-basic-combo-box list="parts" selected="part"></eg-basic-combo-box></div>'+
498             '</div>',
499
500         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@", record: "@" },
501         controller : ['$scope','itemSvc','egCore',
502             function ( $scope , itemSvc , egCore ) {
503                 $scope.new_part_id = 0;
504                 $scope.barcode_has_error = false;
505                 $scope.duplicate_barcode = false;
506                 $scope.empty_barcode = false;
507                 $scope.duplicate_barcode_string = window.duplicate_barcode_string;
508                 $scope.empty_barcode_string = window.empty_barcode_string;
509
510                 if (!$scope.copy.barcode()) $scope.copy.empty_barcode = true;
511
512                 $scope.selectOnFocus = function($event) {
513                     if (!$scope.copy.empty_barcode)
514                         $event.target.select();
515                 }
516
517                 $scope.nextBarcode = function (i) {
518                     $scope.focusNext(i, $scope.barcode);
519                 }
520
521                 $scope.updateBarcode = function () {
522                     if ($scope.barcode != '') {
523                         $scope.copy.empty_barcode = $scope.empty_barcode = false;
524                         $scope.barcode_has_error = !Boolean(itemSvc.checkBarcode($scope.barcode));
525                         itemSvc.checkDuplicateBarcode($scope.barcode, $scope.copy.id())
526                             .then(function (state) { $scope.copy.duplicate_barcode = $scope.duplicate_barcode = state });
527                     } else {
528                         $scope.copy.empty_barcode = $scope.empty_barcode = true;
529                     }
530                         
531                     $scope.copy.barcode($scope.barcode);
532                     $scope.copy.ischanged(1);
533                     if (itemSvc.currently_generating)
534                         $scope.focusNext($scope.copy.id(), $scope.barcode);
535                 };
536
537                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
538                 $scope.updatePart = function () {
539                     if ($scope.part) {
540                         var p = $scope.part_list.filter(function (x) {
541                             return x.label() == $scope.part
542                         });
543                         if (p.length > 0) { // preexisting part
544                             $scope.copy.parts(p)
545                         } else { // create one...
546                             var part = new egCore.idl.bmp();
547                             part.id( --$scope.new_part_id );
548                             part.isnew( true );
549                             part.label( $scope.part );
550                             part.record( $scope.callNumber.record() );
551                             $scope.copy.parts([part]);
552                             $scope.copy.ischanged(1);
553                         }
554                     } else {
555                         $scope.copy.parts([]);
556                     }
557                     $scope.copy.ischanged(1);
558                 }
559
560                 $scope.parts = [];
561                 $scope.part_list = [];
562
563                 itemSvc.get_parts($scope.callNumber.record())
564                 .then(function(list){
565                     $scope.part_list = list;
566                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
567                     $scope.parts = angular.copy($scope.parts);
568                 
569                     $scope.$watch('part', $scope.updatePart);
570                     if ($scope.copy.parts()) {
571                         var the_part = $scope.copy.parts()[0];
572                         if (the_part) $scope.part = the_part.label();
573                     };
574                 });
575
576                 $scope.barcode = $scope.copy.barcode();
577                 $scope.copy_number = $scope.copy.copy_number();
578
579             }
580         ]
581
582     }
583 })
584
585 .directive("egVolRow", function () {
586     return {
587         restrict: 'E',
588         replace: true,
589         transclude: true,
590         template:
591             '<div class="row">'+
592                 '<div class="col-xs-2">'+
593                     '<button aria-label="Delete" style="margin:-5px -15px; float:left;" ng-hide="callNumber.not_ephemeral" type="button" class="close" ng-click="removeCN()">&times;</button>' +
594                     '<select class="form-control" ng-model="classification" ng-change="updateClassification()" ng-options="cl.name() for cl in classification_list"/>'+
595                 '</div>'+
596                 '<div class="col-xs-1">'+
597                     '<select class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list"/>'+
598                 '</div>'+
599                 '<div class="col-xs-2">'+
600                     '<input class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/>'+
601                     '<div class="label label-danger" ng-if="empty_label">{{empty_label_string}}</div>'+
602                 '</div>'+
603                 '<div class="col-xs-1">'+
604                     '<select class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list"/>'+
605                 '</div>'+
606                 '<div ng-hide="onlyVols" class="col-xs-1"><input class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
607                 '<div ng-hide="onlyVols" class="col-xs-5">'+
608                     '<eg-vol-copy-edit record="{{record}}" ng-repeat="cp in copies track by idTracker(cp)" focus-next="focusNextBarcode" copy="cp" call-number="callNumber"></eg-vol-copy-edit>'+
609                 '</div>'+
610             '</div>',
611
612         scope: {focusNext: "=", allcopies: "=", copies: "=", onlyVols: "=", record: "@", struct:"=" },
613         controller : ['$scope','itemSvc','egCore',
614             function ( $scope , itemSvc , egCore ) {
615                 $scope.callNumber =  $scope.copies[0].call_number();
616                 if (!$scope.callNumber.label()) $scope.callNumber.empty_label = true;
617
618                 $scope.empty_label = false;
619                 $scope.empty_label_string = window.empty_label_string;
620
621                 $scope.idTracker = function (x) { if (x && x.id) return x.id() };
622
623                 // XXX $() is not working! arg
624                 $scope.focusNextBarcode = function (i, prev_bc) {
625                     var n;
626                     var yep = false;
627                     angular.forEach($scope.copies, function (cp) {
628                         if (n) return;
629
630                         if (cp.id() == i) {
631                             yep = true;
632                             return;
633                         }
634
635                         if (yep) n = cp.id();
636                     });
637
638                     if (n) {
639                         var next = '#' + $scope.callNumber.id() + '_' + n;
640                         var el = $(next);
641                         if (el) {
642                             if (!itemSvc.currently_generating) el.focus();
643                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
644                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
645                                     el.focus();
646                                     el.val(bc);
647                                     el.trigger('change');
648                                 });
649                             } else {
650                                 itemSvc.currently_generating = false;
651                             }
652                         }
653                     } else {
654                         $scope.focusNext($scope.callNumber.id(),prev_bc)
655                     }
656                 }
657
658                 $scope.suffix_list = [];
659                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
660                     $scope.suffix_list = list;
661                     $scope.$watch('callNumber.suffix()', function (v) {
662                         if (angular.isObject(v)) v = v.id();
663                         $scope.suffix = $scope.suffix_list.filter( function (s) {
664                             return s.id() == v;
665                         })[0];
666                     });
667
668                 });
669                 $scope.updateSuffix = function () {
670                     angular.forEach($scope.copies, function(cp) {
671                         cp.call_number().suffix($scope.suffix);
672                         cp.call_number().ischanged(1);
673                     });
674                 }
675
676                 $scope.prefix_list = [];
677                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
678                     $scope.prefix_list = list;
679                     $scope.$watch('callNumber.prefix()', function (v) {
680                         if (angular.isObject(v)) v = v.id();
681                         $scope.prefix = $scope.prefix_list.filter(function (p) {
682                             return p.id() == v;
683                         })[0];
684                     });
685
686                 });
687                 $scope.updatePrefix = function () {
688                     angular.forEach($scope.copies, function(cp) {
689                         cp.call_number().prefix($scope.prefix);
690                         cp.call_number().ischanged(1);
691                     });
692                 }
693                 $scope.$watch('callNumber.owning_lib()', function(oldLib, newLib) {
694                     if (oldLib == newLib) return;
695                     var currentPrefix = $scope.callNumber.prefix();
696                     if (angular.isObject(currentPrefix)) currentPrefix = currentPrefix.id();
697                     itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
698                         $scope.prefix_list = list;
699                         var newPrefixId = $scope.prefix_list.filter(function (p) {
700                             return p.id() == currentPrefix;
701                         })[0] || -1;
702                         if (newPrefixId.id) newPrefixId = newPrefixId.id();
703                         $scope.prefix = $scope.prefix_list.filter(function (p) {
704                             return p.id() == newPrefixId;
705                         })[0];
706                         if ($scope.newPrefixId != currentPrefix) {
707                             $scope.callNumber.prefix($scope.prefix);
708                         }
709                     });
710                     var currentSuffix = $scope.callNumber.suffix();
711                     if (angular.isObject(currentSuffix)) currentSuffix = currentSuffix.id();
712                     itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
713                         $scope.suffix_list = list;
714                         var newSuffixId = $scope.suffix_list.filter(function (s) {
715                             return s.id() == currentSuffix;
716                         })[0] || -1;
717                         if (newSuffixId.id) newSuffixId = newSuffixId.id();
718                         $scope.suffix = $scope.suffix_list.filter(function (s) {
719                             return s.id() == newSuffixId;
720                         })[0];
721                         if ($scope.newSuffixId != currentSuffix) {
722                             $scope.callNumber.suffix($scope.suffix);
723                         }
724                     });
725                 });
726
727                 $scope.classification_list = [];
728                 itemSvc.get_classifications().then(function(list){
729                     $scope.classification_list = list;
730                     $scope.$watch('callNumber.label_class()', function (v) {
731                         if (angular.isObject(v)) v = v.id();
732                         $scope.classification = $scope.classification_list.filter(function (c) {
733                             return c.id() == v;
734                         })[0];
735                     });
736
737                 });
738                 $scope.updateClassification = function () {
739                     angular.forEach($scope.copies, function(cp) {
740                         cp.call_number().label_class($scope.classification);
741                         cp.call_number().ischanged(1);
742                     });
743                 }
744
745                 $scope.updateLabel = function () {
746                     angular.forEach($scope.copies, function(cp) {
747                         cp.call_number().label($scope.label);
748                         cp.call_number().ischanged(1);
749                     });
750                 }
751
752                 $scope.$watch('callNumber.label()', function (v) {
753                     $scope.label = v;
754                     if ($scope.label == '') {
755                         $scope.callNumber.empty_label = $scope.empty_label = true;
756                     } else {
757                         $scope.callNumber.empty_label = $scope.empty_label = false;
758                     }
759                 });
760
761                 $scope.prefix = $scope.callNumber.prefix();
762                 $scope.suffix = $scope.callNumber.suffix();
763                 $scope.classification = $scope.callNumber.label_class();
764                 $scope.label = $scope.callNumber.label();
765
766                 $scope.copy_count = $scope.copies.length;
767                 $scope.orig_copy_count = $scope.copy_count;
768
769                 $scope.removeCN = function(){
770                     var cn = $scope.callNumber;
771                     if (cn.not_ephemeral) return;  // can't delete existing volumes
772
773                     angular.forEach(Object.keys($scope.struct), function(k){
774                         angular.forEach($scope.struct[k], function(cp){
775                             var struct_cn = cp.call_number();
776                             if (struct_cn.id() == cn.id()){
777                                 console.log("X'ed CN id" + cn.id() + " and struct CN id match!");
778                                 // remove any copies in $scope.struct[k]
779                                 angular.forEach($scope.copies, function(c){
780                                     var idx = $scope.allcopies.indexOf(c);
781                                     $scope.allcopies.splice(idx, 1);
782                                 });
783
784                                 $scope.copies = [];
785                                 // remove added vol:
786                                 delete $scope.struct[k];
787                             }
788                         });
789                     });
790
791                     // manually decrease cn_count numeric input
792                     var cn_spinner = $("input[name='cn_count_lib"+ cn.owning_lib() +"']");
793                     if (cn_spinner.val() > 0) cn_spinner.val(parseInt(cn_spinner.val()) - 1);
794                     cn_spinner.trigger("change");
795
796                 }
797
798                 $scope.changeCPCount = function () {
799                     while ($scope.copy_count > $scope.copies.length) {
800                         var cp = itemSvc.generateNewCopy(
801                             $scope.callNumber,
802                             $scope.callNumber.owning_lib(),
803                             $scope.fast_add,
804                             true
805                         );
806                         $scope.copies.push( cp );
807                         $scope.allcopies.push( cp );
808
809                     }
810
811                     if ($scope.copy_count >= $scope.orig_copy_count) {
812                         var how_many = $scope.copies.length - $scope.copy_count;
813                         if (how_many > 0) {
814                             var dead = $scope.copies.splice($scope.copy_count,how_many);
815                             $scope.callNumber.copies($scope.copies);
816
817                             // Trimming the global list is a bit more tricky
818                             angular.forEach( dead, function (d) {
819                                 angular.forEach( $scope.allcopies, function (l, i) { 
820                                     if (l === d) $scope.allcopies.splice(i,1);
821                                 });
822                             });
823                         }
824                     }
825                 }
826
827             }
828         ]
829
830     }
831 })
832
833 .directive("egVolEdit", function () {
834     return {
835         restrict: 'E',
836         replace: true,
837         template:
838             '<div class="row">'+
839                 '<div class="col-xs-1"><eg-org-selector selected="owning_lib" disable-test="cant_have_vols"></eg-org-selector></div>'+
840                 '<div class="col-xs-1"><input class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
841                 '<div class="col-xs-10">'+
842                     '<eg-vol-row only-vols="onlyVols" record="{{record}}"'+
843                         'ng-repeat="(cn,copies) in struct" '+
844                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies" struct="struct">'+
845                     '</eg-vol-row>'+
846                 '</div>'+
847             '</div>',
848
849         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
850         controller : ['$scope','itemSvc','egCore',
851             function ( $scope , itemSvc , egCore ) {
852                 $scope.first_cn = Object.keys($scope.struct)[0];
853                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
854
855                 $scope.defaults = {};
856                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
857                     if (t) {
858                         $scope.defaults = t;
859                     }
860                 });
861
862                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
863                     var n;
864                     var yep = false;
865                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
866                         if (n) return;
867
868                         if (cn == prev_cn) {
869                             yep = true;
870                             return;
871                         }
872
873                         if (yep) n = cn;
874                     });
875
876                     if (n) {
877                         var next = '#' + n + '_' + $scope.struct[n][0].id();
878                         var el = $(next);
879                         if (el) {
880                             if (!itemSvc.currently_generating) el.focus();
881                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
882                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
883                                     el.focus();
884                                     el.val(bc);
885                                     el.trigger('change');
886                                 });
887                             } else {
888                                 itemSvc.currently_generating = false;
889                             }
890                         }
891                     } else {
892                         $scope.focusNext($scope.lib, prev_bc);
893                     }
894                 }
895
896                 $scope.cn_count = Object.keys($scope.struct).length;
897                 $scope.orig_cn_count = $scope.cn_count;
898
899                 $scope.owning_lib = egCore.org.get($scope.lib);
900                 $scope.$watch('owning_lib', function (oldLib, newLib) {
901                     if (oldLib == newLib) return;
902                     angular.forEach( Object.keys($scope.struct), function (cn) {
903                         $scope.struct[cn][0].call_number().owning_lib( $scope.owning_lib.id() );
904                         $scope.struct[cn][0].call_number().ischanged(1);
905                     });
906                 });
907
908                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
909
910                 $scope.$watch('cn_count', function (n) {
911                     var o = Object.keys($scope.struct).length;
912                     if (n > o) { // adding
913                         for (var i = o; o < n; o++) {
914                             var cn = new egCore.idl.acn();
915                             cn.id( --itemSvc.new_cn_id );
916                             cn.isnew( true );
917                             cn.prefix( $scope.defaults.prefix || -1 );
918                             cn.suffix( $scope.defaults.suffix || -1 );
919                             cn.label_class( $scope.defaults.classification || 1 );
920                             cn.owning_lib( $scope.owning_lib.id() );
921                             cn.record( $scope.full_cn.record() );
922
923                             var cp = itemSvc.generateNewCopy(
924                                 cn,
925                                 $scope.owning_lib.id(),
926                                 $scope.fast_add,
927                                 true
928                             );
929
930                             $scope.struct[cn.id()] = [cp];
931                             $scope.allcopies.push(cp);
932                             if (!$scope.defaults.classification) {
933                                 egCore.org.settings(
934                                     ['cat.default_classification_scheme'],
935                                     cn.owning_lib()
936                                 ).then(function (val) {
937                                     cn.label_class(val['cat.default_classification_scheme']);
938                                 });
939                             }
940                         }
941                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
942                         var how_many = o - n;
943                         var list = Object
944                                 .keys($scope.struct)
945                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
946                                 .filter(function(x){ return parseInt(x) <= 0 });
947                         for (var i = 0; i < how_many; i++) {
948                             // Trimming the global list is a bit more tricky
949                             angular.forEach($scope.struct[list[i]], function (d) {
950                                 angular.forEach( $scope.allcopies, function (l, j) { 
951                                     if (l === d) $scope.allcopies.splice(j,1);
952                                 });
953                             });
954                             delete $scope.struct[list[i]];
955                         }
956                     }
957                 });
958             }
959         ]
960
961     }
962 })
963
964 /**
965  * Edit controller!
966  */
967 .controller('EditCtrl', 
968        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$uibModal',
969 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $uibModal) {
970
971     $scope.forms = {}; // Accessed by t_attr_edit.tt2
972     $scope.i18n = egCore.i18n;
973
974     $scope.defaults = { // If defaults are not set at all, allow everything
975         barcode_checkdigit : false,
976         auto_gen_barcode : false,
977         statcats : true,
978         copy_notes : true,
979         copy_tags : true,
980         attributes : {
981             status : true,
982             loan_duration : true,
983             fine_level : true,
984             cost : true,
985             alerts : true,
986             deposit : true,
987             deposit_amount : true,
988             opac_visible : true,
989             price : true,
990             circulate : true,
991             mint_condition : true,
992             circ_lib : true,
993             ref : true,
994             circ_modifier : true,
995             circ_as_type : true,
996             location : true,
997             holdable : true,
998             age_protect : true,
999             floating : true,
1000             alerts : true
1001         }
1002     };
1003
1004     $scope.new_lib_to_add = egCore.org.get(egCore.auth.user().ws_ou());
1005     $scope.changeNewLib = function (org) {
1006         $scope.new_lib_to_add = org;
1007     }
1008     $scope.addLibToStruct = function () {
1009         var newLib = $scope.new_lib_to_add;
1010         var cn = new egCore.idl.acn();
1011         cn.id( --itemSvc.new_cn_id );
1012         cn.isnew( true );
1013         cn.prefix( $scope.defaults.prefix || -1 );
1014         cn.suffix( $scope.defaults.suffix || -1 );
1015         cn.label_class( $scope.defaults.classification || 1 );
1016         cn.owning_lib( newLib.id() );
1017         cn.record( $scope.record_id );
1018
1019         var cp = itemSvc.generateNewCopy(
1020             cn,
1021             newLib.id(),
1022             $scope.fast_add,
1023             true
1024         );
1025
1026         $scope.data.addCopy(cp);
1027
1028         // manually increase cn_count numeric input
1029         var cn_spinner = $("input[name='cn_count_lib"+ newLib.id() +"']");
1030         cn_spinner.val(parseInt(cn_spinner.val()) + 1);
1031         cn_spinner.trigger("change");
1032
1033         if (!$scope.defaults.classification) {
1034             egCore.org.settings(
1035                 ['cat.default_classification_scheme'],
1036                 cn.owning_lib()
1037             ).then(function (val) {
1038                 cn.label_class(val['cat.default_classification_scheme']);
1039             });
1040         }
1041     }
1042
1043     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
1044     $scope.edit_templates = ($location.path().match(/edit_template/)) ? true : false;
1045
1046     $scope.saveDefaults = function () {
1047         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
1048     }
1049
1050     $scope.fetchDefaults = function () {
1051         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1052             if (t) {
1053                 $scope.defaults = t;
1054                 if (!$scope.batch) $scope.batch = {};
1055                 $scope.batch.classification = $scope.defaults.classification;
1056                 $scope.batch.prefix = $scope.defaults.prefix;
1057                 $scope.batch.suffix = $scope.defaults.suffix;
1058                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1059                 if (
1060                         typeof $scope.defaults.statcat_filter == 'object' &&
1061                         Object.keys($scope.defaults.statcat_filter).length > 0
1062                    ) {
1063                     // want fieldmapper object here...
1064                     $scope.defaults.statcat_filter =
1065                          egCore.idl.Clone($scope.defaults.statcat_filter);
1066                     // ... and ID here
1067                     $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
1068                 }
1069                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
1070                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
1071                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
1072             }
1073
1074             // Fetch the list of bib-level callnumbers based on the applied
1075             // classification scheme.  If none is defined, default to "1"
1076             // (Generic) since it provides the most options.
1077             egCore.net.request(
1078                 'open-ils.cat',
1079                 'open-ils.cat.biblio.record.marc_cn.retrieve',
1080                 $scope.record_id,
1081                 $scope.batch.classification || 1
1082             ).then(function(list) {
1083                 $scope.batch.marcCallNumbers = [];
1084                 list.forEach(function(hash) {
1085                     $scope.batch.marcCallNumbers.push(Object.values(hash)[0]);
1086                 });
1087             });
1088         });
1089     }
1090
1091     $scope.$watch('defaults.statcat_filter', function() {
1092         $scope.saveDefaults();
1093     });
1094     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
1095         itemSvc.auto_gen_barcode = n
1096     });
1097
1098     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
1099         itemSvc.barcode_checkdigit = n
1100     });
1101
1102     $scope.dirty = false;
1103     $scope.$watch('dirty',
1104         function(newVal, oldVal) {
1105             if (newVal && newVal != oldVal) {
1106                 $($window).on('beforeunload.edit', function(){
1107                     return 'There is unsaved data!'
1108                 });
1109             } else {
1110                 $($window).off('beforeunload.edit');
1111             }
1112         }
1113     );
1114
1115     $scope.only_vols = false;
1116     $scope.show_vols = true;
1117     $scope.show_copies = true;
1118
1119     $scope.tracker = function (x,f) { if (x) return x[f]() };
1120     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1121     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1122
1123     $scope.orgById = function (id) { return egCore.org.get(id) }
1124     $scope.statusById = function (id) {
1125         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1126     }
1127     $scope.locationById = function (id) {
1128         return $scope.location_cache[''+id];
1129     }
1130
1131     $scope.workingToComplete = function () {
1132         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
1133             angular.forEach( itemSvc.copies, function (w, i) {
1134                 if (c === w)
1135                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
1136             });
1137         });
1138
1139         return true;
1140     }
1141
1142     $scope.completeToWorking = function () {
1143         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
1144             angular.forEach( $scope.completed_copies, function (w, i) {
1145                 if (c === w)
1146                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
1147             });
1148         });
1149
1150         return true;
1151     }
1152
1153     createSimpleUpdateWatcher = function (field,exclude_copies_with_one_of_these_values) {
1154         return $scope.$watch('working.' + field, function () {
1155             var newval = $scope.working[field];
1156
1157             if (typeof newval != 'undefined') {
1158                 delete $scope.working.MultiMap[field];
1159                 if (angular.isObject(newval)) { // we'll use the pkey
1160                     if (newval.id) newval = newval.id();
1161                     else if (newval.code) newval = newval.code();
1162                 }
1163
1164                 if (""+newval == "" || newval == null) {
1165                     $scope.working[field] = undefined;
1166                     newval = null;
1167                 }
1168
1169                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1170                     angular.forEach(
1171                         $scope.workingGridControls.selectedItems(),
1172                         function (cp) {
1173                             if (exclude_copies_with_one_of_these_values
1174                                 && exclude_copies_with_one_of_these_values.indexOf(cp[field](),0) > -1) {
1175                                 return;
1176                             }
1177                             if (cp[field]() !== newval) {
1178                                 cp[field](newval);
1179                                 cp.ischanged(1);
1180                                 $scope.dirty = true;
1181                             }
1182                         }
1183                     );
1184                 }
1185             }
1186         });
1187     }
1188
1189     $scope.working = {
1190         MultiMap: {},
1191         statcats: {},
1192         statcats_multi: {},
1193         statcat_filter: undefined
1194     };
1195
1196     // Returns true if we are editing multiple copies and at least
1197     // one field contains multiple values.
1198     $scope.hasMulti = function() {
1199         var keys = Object.keys($scope.working.MultiMap);
1200         // for-loop for shortcut exit
1201         for (var i = 0; i < keys.length; i++) {
1202             if ($scope.working.MultiMap[keys[i]].length > 1) {
1203                 return true;
1204             }
1205         }
1206         return false;
1207     }
1208
1209     $scope.copyAlertUpdate = function (alerts) {
1210         if (!$scope.in_item_select &&
1211             $scope.workingGridControls &&
1212             $scope.workingGridControls.selectedItems) {
1213             itemSvc.get_copy_alert_types().then(function(ccat) {
1214                 var ccat_map = {};
1215                 $scope.alert_types = ccat;
1216                 angular.forEach(ccat, function(t) {
1217                     ccat_map[t.id()] = t;
1218                 });
1219                 angular.forEach(
1220                     $scope.workingGridControls.selectedItems(),
1221                     function (cp) {
1222                         $scope.dirty = true;
1223                         angular.forEach(alerts, function(alrt) {
1224                             var a = egCore.idl.fromHash('aca', alrt);
1225                             a.isnew(1);
1226                             a.create_staff(egCore.auth.user().id());
1227                             a.alert_type(ccat_map[a.alert_type()]);
1228                             a.ack_time(null);
1229                             a.copy(cp.id());
1230                             cp.copy_alerts().push( a );
1231                         });
1232                         cp.ischanged(1);
1233                     }
1234                 );
1235             });
1236         }
1237     };
1238
1239     $scope.copyNoteUpdate = function (notes) {
1240         if (!$scope.in_item_select &&
1241             $scope.workingGridControls &&
1242             $scope.workingGridControls.selectedItems) {
1243             angular.forEach(
1244                 $scope.workingGridControls.selectedItems(),
1245                 function (cp) {
1246                     $scope.dirty = true;
1247                     angular.forEach(notes, function(note) {
1248                         var n = egCore.idl.fromHash('acpn', note);
1249                         n.isnew(1);
1250                         n.creator(egCore.auth.user().id());
1251                         n.owning_copy(cp.id());
1252                         cp.notes().push( n );
1253                     });
1254                     cp.ischanged(1);
1255                 }
1256             );
1257
1258         }
1259     }
1260
1261     $scope.statcatUpdate = function (id) {
1262         var newval = $scope.working.statcats[id];
1263
1264         if (typeof newval != 'undefined') {
1265             if (angular.isObject(newval)) { // we'll use the pkey
1266                 newval = newval.id();
1267             }
1268     
1269             if (""+newval == "" || newval == null) {
1270                 $scope.working.statcats[id] = undefined;
1271                 newval = null;
1272             }
1273     
1274             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1275                 angular.forEach(
1276                     $scope.workingGridControls.selectedItems(),
1277                     function (cp) {
1278                         $scope.dirty = true;
1279
1280                         cp.stat_cat_entries(
1281                             angular.forEach( cp.stat_cat_entries(), function (e) {
1282                                 if (e.stat_cat() == id) { // mark deleted
1283                                     e.isdeleted(1);
1284                                 }
1285                             })
1286                         );
1287     
1288                         if (newval) {
1289                             var e = new egCore.idl.asce();
1290                             e.isnew( 1 );
1291                             e.stat_cat( id );
1292                             e.id(newval);
1293
1294                             cp.stat_cat_entries(
1295                                 cp.stat_cat_entries() ?
1296                                     cp.stat_cat_entries().concat([ e ]) :
1297                                     [ e ]
1298                             );
1299
1300                         }
1301
1302                         // trim out all deleted ones; the API used to
1303                         // do the update doesn't actually consult
1304                         // isdeleted for stat cat entries
1305                         if (cp.stat_cat_entries()) {
1306                             cp.stat_cat_entries(
1307                                 cp.stat_cat_entries().filter(function (e) {
1308                                     return !Boolean(e.isdeleted());
1309                                 })
1310                             );
1311                         }
1312    
1313                         cp.ischanged(1);
1314                     }
1315                 );
1316             }
1317         }
1318     }
1319
1320     var dataKey = $routeParams.dataKey;
1321     console.debug('dataKey: ' + dataKey);
1322
1323     if ((dataKey && dataKey.length > 0) || $scope.edit_templates) {
1324
1325         $scope.templates = {};
1326         $scope.template_name = '';
1327         $scope.template_name_list = [];
1328
1329         $scope.fetchTemplates = function () {
1330             itemSvc.get_acp_templates().then(function(t) {
1331                 if (t) {
1332                     $scope.templates = t;
1333                     $scope.template_name_list = Object.keys(t).sort();
1334                 }
1335             });
1336             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
1337                 if (t) $scope.template_name = t;
1338             });
1339         }
1340         $scope.fetchTemplates();
1341
1342         $scope.applyTemplate = function (n) {
1343             angular.forEach($scope.templates[n], function (v,k) {
1344                 if (k == 'circ_lib') {
1345                     $scope.working[k] = egCore.org.get(v);
1346                 } else if (k == 'copy_notes' && v.length) {
1347                     $scope.copyNoteUpdate(v);
1348                 } else if (k == 'copy_alerts' && v.length) {
1349                     $scope.copyAlertUpdate(v);
1350                 } else if (!angular.isObject(v)) {
1351                     $scope.working[k] = angular.copy(v);
1352                 } else {
1353                     angular.forEach(v, function (sv,sk) {
1354                         if (k == 'callnumber') {
1355                             angular.forEach(v, function (cnv,cnk) {
1356                                 $scope.batch[cnk] = cnv;
1357                             });
1358                             $scope.applyBatchCNValues();
1359                         } else {
1360                             $scope.working[k][sk] = angular.copy(sv);
1361                             if (k == 'statcats') $scope.statcatUpdate(sk);
1362                         }
1363                     });
1364                 }
1365                 delete $scope.working.MultiMap[k];
1366             });
1367             egCore.hatch.setItem('cat.copy.last_template', n);
1368         }
1369
1370         $scope.copytab = 'working';
1371         $scope.tab = 'edit';
1372         $scope.summaryRecord = null;
1373         $scope.record_id = null;
1374         $scope.data = {};
1375         $scope.completed_copies = [];
1376         $scope.location_orgs = [];
1377         $scope.location_cache = {};
1378         $scope.statcats = [];
1379         if (!$scope.batch) $scope.batch = {};
1380
1381         $scope.applyBatchCNValues = function () {
1382             if ($scope.data.tree) {
1383                 angular.forEach($scope.data.tree, function(cn_hash) {
1384                     angular.forEach(cn_hash, function(copies) {
1385                         angular.forEach(copies, function(cp) {
1386                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
1387                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
1388                                 cp.call_number().label_class(label_class);
1389                                 cp.call_number().ischanged(1);
1390                                 $scope.dirty = true;
1391                             }
1392                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
1393                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
1394                                 cp.call_number().prefix(prefix);
1395                                 cp.call_number().ischanged(1);
1396                                 $scope.dirty = true;
1397                             }
1398                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
1399                                 cp.call_number().label($scope.batch.label);
1400                                 cp.call_number().ischanged(1);
1401                                 $scope.dirty = true;
1402                             }
1403                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
1404                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
1405                                 cp.call_number().suffix(suffix);
1406                                 cp.call_number().ischanged(1);
1407                                 $scope.dirty = true;
1408                             }
1409                         });
1410                     });
1411                 });
1412             }
1413         }
1414
1415         $scope.clearWorking = function () {
1416             angular.forEach($scope.working, function (v,k,o) {
1417                 if (!angular.isObject(v)) {
1418                     if (typeof v != 'undefined')
1419                         $scope.working[k] = undefined;
1420                 } else if (k != 'circ_lib') {
1421                     angular.forEach(v, function (sv,sk) {
1422                         if (typeof v != 'undefined')
1423                             $scope.working[k][sk] = undefined;
1424                     });
1425                 }
1426             });
1427             $scope.working.circ_lib = undefined; // special
1428         }
1429
1430         $scope.completedGridDataProvider = egGridDataProvider.instance({
1431             get : function(offset, count) {
1432                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1433                 return this.arrayNotifier($scope.completed_copies, offset, count);
1434             }
1435         });
1436
1437         $scope.completedGridControls = {};
1438
1439         $scope.workingGridDataProvider = egGridDataProvider.instance({
1440             get : function(offset, count) {
1441                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1442                 return this.arrayNotifier(itemSvc.copies, offset, count);
1443             }
1444         });
1445
1446         $scope.workingGridControls = {};
1447         $scope.add_vols_copies = false;
1448         $scope.is_fast_add = false;
1449
1450         // Generate some functions for selecting items by column value in the working grid
1451         angular.forEach(
1452             ['circulate','status','circ_lib','ref','location','opac_visible','circ_modifier','price',
1453              'loan_duration','cost','circ_as_type','deposit','holdable','deposit_amount','age_protect',
1454              'mint_condition','fine_level','floating'],
1455             function (field) {
1456                 $scope['select_by_' + field] = function (x) {
1457                     $scope.workingGridControls.selectItemsByValue(field,x);
1458                 }
1459             }
1460         );
1461
1462         var truthy = /^t|1/;
1463         $scope.labelYesNo = function (x) {
1464             return truthy.test(x) ? egCore.strings.YES : egCore.strings.NO;
1465         }
1466
1467         $scope.orgShortname = function (x) {
1468             return egCore.org.get(x).shortname();
1469         }
1470
1471         $scope.statusName = function (x) {
1472             var s = $scope.status_list.filter(function(y) {
1473                 return y.id() == x;
1474             });
1475
1476             return s[0].name();
1477         }
1478
1479         $scope.locationName = function (x) {
1480             var s = $scope.location_list.filter(function(y) {
1481                 return y.id() == x;
1482             });
1483
1484             return $scope.i18n.ou_qualified_location_name(s[0]);
1485         }
1486
1487         $scope.durationLabel = function (x) {
1488             return [egCore.strings.SHORT, egCore.strings.NORMAL, egCore.strings.EXTENDED][-1 + x]
1489         }
1490
1491         $scope.fineLabel = function (x) {
1492             return [egCore.strings.LOW, egCore.strings.NORMAL, egCore.strings.HIGH][-1 + x]
1493         }
1494
1495         $scope.circTypeValue = function (x) {
1496             if (x === null || x === undefined) return egCore.strings.UNSET;
1497             var s = $scope.circ_type_list.filter(function(y) {
1498                 return y.code() == x;
1499             });
1500
1501             return s[0].value();
1502         }
1503
1504         $scope.ageprotectName = function (x) {
1505             if (x === null || x === undefined) return egCore.strings.UNSET;
1506             var s = $scope.age_protect_list.filter(function(y) {
1507                 return y.id() == x;
1508             });
1509
1510             return s[0].name();
1511         }
1512
1513         $scope.floatingName = function (x) {
1514             if (x === null || x === undefined) return egCore.strings.UNSET;
1515             var s = $scope.floating_list.filter(function(y) {
1516                 return y.id() == x;
1517             });
1518
1519             return s[0].name();
1520         }
1521
1522         $scope.circmodName = function (x) {
1523             if (x === null || x === undefined) return egCore.strings.UNSET;
1524             var s = $scope.circ_modifier_list.filter(function(y) {
1525                 return y.code() == x;
1526             });
1527
1528             return s[0].name();
1529         }
1530
1531         egNet.request(
1532             'open-ils.actor',
1533             'open-ils.actor.anon_cache.get_value',
1534             dataKey, 'edit-these-copies'
1535         ).then(function (data) {
1536
1537             if (data) {
1538                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1539                 if (data.hide_copies) {
1540                     $scope.show_copies = false;
1541                     $scope.only_vols = true;
1542                 }
1543
1544                 $scope.record_id = data.record_id;
1545
1546                 // Fetch defaults 
1547                 $scope.fetchDefaults();
1548
1549                 function fetchRaw () {
1550                     if (!$scope.only_vols) $scope.dirty = true;
1551                     $scope.add_vols_copies = true;
1552
1553                     /* data.raw data structure looks like this:
1554                      * [{
1555                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1556                      *      owner      : $org, // optional, defaults to cn.owning_lib or ws_ou
1557                      *      label      : $cn_label, // optional, to supply a label on a new cn
1558                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1559                      *      fast_add   : boolean // optional, to specify whether this came
1560                      *                              in as a fast add
1561                      * },...]
1562                      * 
1563                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1564                      */
1565
1566                     var promises = [];
1567                     angular.forEach(
1568                         data.raw,
1569                         function (proto) {
1570                             if (proto.fast_add) $scope.is_fast_add = true;
1571                             if (proto.callnumber) {
1572                                 promises.push(egCore.pcrud.retrieve('acn', proto.callnumber)
1573                                 .then(function(cn) {
1574                                     var cp = new itemSvc.generateNewCopy(
1575                                         cn,
1576                                         proto.owner || cn.owning_lib(),
1577                                         $scope.is_fast_add,
1578                                         ((!$scope.only_vols) ? true : false)
1579                                     );
1580
1581                                     if (proto.barcode) {
1582                                         cp.barcode( proto.barcode );
1583                                         cp.empty_barcode = false;
1584                                     }
1585
1586                                     itemSvc.addCopy(cp)
1587                                 }));
1588                             } else {
1589                                 var cn = new egCore.idl.acn();
1590                                 cn.id( --itemSvc.new_cn_id );
1591                                 cn.isnew( true );
1592                                 cn.prefix( $scope.defaults.prefix || -1 );
1593                                 cn.suffix( $scope.defaults.suffix || -1 );
1594                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1595                                 cn.record( $scope.record_id );
1596                                 egCore.org.settings(
1597                                     ['cat.default_classification_scheme'],
1598                                     cn.owning_lib()
1599                                 ).then(function (val) {
1600                                     cn.label_class(
1601                                         $scope.defaults.classification ||
1602                                         val['cat.default_classification_scheme'] ||
1603                                         1
1604                                     );
1605                                     if (proto.label) {
1606                                         cn.label( proto.label );
1607                                     } else {
1608                                         egCore.net.request(
1609                                             'open-ils.cat',
1610                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1611                                             $scope.record_id,
1612                                             cn.label_class()
1613                                         ).then(function(cn_array) {
1614                                             if (cn_array.length > 0) {
1615                                                 for (var field in cn_array[0]) {
1616                                                     cn.label( cn_array[0][field] );
1617                                                     break;
1618                                                 }
1619                                             }
1620                                         });
1621                                     }
1622                                 });
1623
1624                                 // If we are adding an empty vol,
1625                                 // this is ultimately just a placeholder copy
1626                                 // which gets removed before saving.
1627                                 // TODO: consider ways to remove this
1628                                 // requirement
1629                                 var cp = new itemSvc.generateNewCopy(
1630                                     cn,
1631                                     proto.owner || cn.owning_lib(),
1632                                     $scope.is_fast_add,
1633                                     true
1634                                 );
1635
1636                                 if (proto.barcode) {
1637                                     cp.barcode( proto.barcode );
1638                                     cp.empty_barcode = false;
1639                                 }
1640
1641                                 itemSvc.addCopy(cp)
1642                             }
1643                         }
1644                     );
1645
1646                     angular.forEach(itemSvc.copies, function(c){
1647                         var cn = c.call_number();
1648                         var copy_id = c.id();
1649                         if (copy_id > 0){
1650                             cn.not_ephemeral = true;
1651                         }
1652                     });
1653
1654                     return $q.all(promises);
1655                 }
1656
1657                 if (data.copies && data.copies.length)
1658                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1659
1660                 return fetchRaw();
1661
1662             }
1663
1664         }).then( function() {
1665
1666             return itemSvc.fetch_locations(
1667                 itemSvc.copies.map(function(cp){
1668                     return cp.location();
1669                 }).filter(function(e,i,a){
1670                     return a.lastIndexOf(e) === i;
1671                 })
1672             ).then(function(list){
1673                 $scope.data = itemSvc;
1674                 $scope.location_list = list;
1675                 $scope.workingGridDataProvider.refresh();
1676             });
1677
1678         });
1679
1680         $scope.can_save = false;
1681         function check_saveable () {
1682             var can_save = true;
1683
1684             angular.forEach(
1685                 itemSvc.copies,
1686                 function (i) {
1687                     if (!$scope.only_vols) {
1688                         if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label) {
1689                             can_save = false;
1690                         }
1691                     } else if (i.call_number().empty_label) {
1692                         can_save = false;
1693                     }
1694                 }
1695             );
1696
1697             if (!$scope.only_vols && $scope.forms.myForm && $scope.forms.myForm.$invalid) {
1698                 can_save = false;
1699             }
1700
1701             $scope.can_save = can_save;
1702         }
1703
1704         $scope.disableSave = function () {
1705             check_saveable();
1706             return !$scope.can_save;
1707         }
1708
1709         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1710             var n;
1711             var yep = false;
1712             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1713                 if (n) return;
1714
1715                 if (lib == prev_lib) {
1716                     yep = true;
1717                     return;
1718                 }
1719
1720                 if (yep) n = lib;
1721             });
1722
1723             if (n) {
1724                 var first_cn = Object.keys($scope.data.tree[n])[0];
1725                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1726                 var el = $(next);
1727                 if (el) {
1728                     if (!itemSvc.currently_generating) el.focus();
1729                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1730                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1731                             el.focus();
1732                             el.val(bc);
1733                             el.trigger('change');
1734                         });
1735                     } else {
1736                         itemSvc.currently_generating = false;
1737                     }
1738                 }
1739             }
1740         }
1741
1742         $scope.in_item_select = false;
1743         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1744         $scope.handleItemSelect = function (item_list) {
1745             if (item_list && item_list.length > 0) {
1746                 $scope.in_item_select = true;
1747
1748                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1749
1750                     var value_hash = {};
1751                     var value_list = [];
1752                     angular.forEach(item_list, function (item) {
1753                         if (item[attr]) {
1754                             var v = item[attr]()
1755                             if (angular.isObject(v)) {
1756                                 if (v.id) v = v.id();
1757                                 else if (v.code) v = v.code();
1758                             }
1759                             value_list.push(v);
1760                             value_hash[v] = 1;
1761                         }
1762                     });
1763
1764                     $scope.working.MultiMap[attr] = value_list;
1765
1766                     if (Object.keys(value_hash).length == 1) {
1767                         if (attr == 'circ_lib') {
1768                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1769                         } else {
1770                             $scope.working[attr] = item_list[0][attr]();
1771                         }
1772                     } else {
1773                         $scope.working[attr] = undefined;
1774                     }
1775                 });
1776
1777                 angular.forEach($scope.statcats, function (sc) {
1778
1779                     var counter = -1;
1780                     var value_hash = {};
1781                     var none = false;
1782                     angular.forEach(item_list, function (item) {
1783                         if (item.stat_cat_entries()) {
1784                             if (item.stat_cat_entries().length > 0) {
1785                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1786                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1787                                 });
1788
1789                                 if (right_sc.length > 0) {
1790                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1791                                 } else {
1792                                     none = true;
1793                                 }
1794                             } else {
1795                                 none = true;
1796                             }
1797                         } else {
1798                             none = true;
1799                         }
1800                     });
1801
1802                     if (!none && Object.keys(value_hash).length == 1) {
1803                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1804                         $scope.working.statcats_multi[sc.id()] = false;
1805                     } else if (item_list.length > 1 && Object.keys(value_hash).length > 0) {
1806                         $scope.working.statcats[sc.id()] = undefined;
1807                         $scope.working.statcats_multi[sc.id()] = true;
1808                     } else {
1809                         $scope.working.statcats[sc.id()] = undefined;
1810                         $scope.working.statcats_multi[sc.id()] = false;
1811                     }
1812
1813                 });
1814
1815             } else {
1816                 $scope.clearWorking();
1817             }
1818
1819         }
1820
1821         $scope.$watch('data.copies.length', function () {
1822             if ($scope.data.copies) {
1823                 var base_orgs = $scope.data.copies.map(function(cp){
1824                     if (isNaN(cp.circ_lib())) return Number(cp.circ_lib().id());
1825                     return Number(cp.circ_lib());
1826                 }).concat(
1827                     $scope.data.copies.map(function(cp){
1828                         if (isNaN(cp.call_number().owning_lib())) return Number(cp.call_number().owning_lib().id());
1829                         return Number(cp.call_number().owning_lib());
1830                     })
1831                 ).concat(
1832                     [egCore.auth.user().ws_ou()]
1833                 ).filter(function(e,i,a){
1834                     return a.lastIndexOf(e) === i;
1835                 });
1836
1837                 var all_orgs = [];
1838                 angular.forEach(base_orgs, function(o) {
1839                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1840                 });
1841
1842                 var final_orgs = all_orgs.filter(function(e,i,a){
1843                     return a.lastIndexOf(e) === i;
1844                 }).sort(function(a, b){return a-b});
1845
1846                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1847                     $scope.location_orgs = final_orgs;
1848                     if ($scope.location_orgs.length) {
1849                         itemSvc.get_locations_by_org($scope.location_orgs).then(function(list){
1850                             angular.forEach(list, function(l) {
1851                                 $scope.location_cache[ ''+l.id() ] = l;
1852                             });
1853                             $scope.location_list = list;
1854                         }).then(function() {
1855                             $scope.statcat_filter_list = [];
1856                             angular.forEach($scope.location_orgs, function (o) {
1857                                 $scope.statcat_filter_list.push(egCore.org.get(o));
1858                             });
1859
1860                             itemSvc.get_statcats($scope.location_orgs).then(function(list){
1861                                 $scope.statcats = list;
1862                                 angular.forEach($scope.statcats, function (s) {
1863
1864                                     if (!$scope.working)
1865                                         $scope.working = { statcats_multi: {}, statcats: {}, statcat_filter: undefined};
1866                                     if (!$scope.working.statcats_multi)
1867                                         $scope.working.statcats_multi = {};
1868                                     if (!$scope.working.statcats)
1869                                         $scope.working.statcats = {};
1870
1871                                     if (!$scope.in_item_select) {
1872                                         $scope.working.statcats[s.id()] = undefined;
1873                                     }
1874                                     createStatcatUpdateWatcher(s.id());
1875                                 });
1876                                 $scope.in_item_select = false;
1877                                 // do a refresh here to work around a race
1878                                 // condition that can result in stat cats
1879                                 // not being selected.
1880                                 $scope.workingGridDataProvider.refresh();
1881                             });
1882                         });
1883                     }
1884                 } else {
1885                     $scope.workingGridDataProvider.refresh();
1886                 }
1887             }
1888         });
1889
1890         $scope.statcat_visible = function (sc_owner) {
1891             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1892             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1893                 if ($scope.working.statcat_filter == ancestor_org.id())
1894                     visible = true;
1895             });
1896             return visible;
1897         }
1898
1899         $scope.suffix_list = [];
1900         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1901             $scope.suffix_list = list;
1902         });
1903
1904         $scope.prefix_list = [];
1905         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1906             $scope.prefix_list = list;
1907         });
1908
1909         $scope.classification_list = [];
1910         itemSvc.get_classifications().then(function(list){
1911             $scope.classification_list = list;
1912         });
1913
1914         $scope.$watch('completed_copies.length', function () {
1915             $scope.completedGridDataProvider.refresh();
1916         });
1917
1918         $scope.location_list = [];
1919         createSimpleUpdateWatcher('location');
1920
1921         $scope.status_list = [];
1922         itemSvc.get_magic_statuses().then(function(list){
1923             $scope.magic_status_list = list;
1924             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1925         });
1926         itemSvc.get_statuses().then(function(list){
1927             $scope.status_list = list;
1928         });
1929
1930         $scope.circ_modifier_list = [];
1931         itemSvc.get_circ_mods().then(function(list){
1932             $scope.circ_modifier_list = list;
1933         });
1934         createSimpleUpdateWatcher('circ_modifier');
1935
1936         $scope.circ_type_list = [];
1937         itemSvc.get_circ_types().then(function(list){
1938             $scope.circ_type_list = list;
1939         });
1940         createSimpleUpdateWatcher('circ_as_type');
1941
1942         $scope.age_protect_list = [];
1943         itemSvc.get_age_protects().then(function(list){
1944             $scope.age_protect_list = list;
1945         });
1946         createSimpleUpdateWatcher('age_protect');
1947
1948         $scope.floating_list = [];
1949         itemSvc.get_floating_groups().then(function(list){
1950             $scope.floating_list = list;
1951         });
1952         createSimpleUpdateWatcher('floating');
1953
1954         createSimpleUpdateWatcher('circ_lib');
1955         createSimpleUpdateWatcher('circulate');
1956         createSimpleUpdateWatcher('holdable');
1957         createSimpleUpdateWatcher('fine_level');
1958         createSimpleUpdateWatcher('loan_duration');
1959         createSimpleUpdateWatcher('price');
1960         createSimpleUpdateWatcher('cost');
1961         createSimpleUpdateWatcher('deposit');
1962         createSimpleUpdateWatcher('deposit_amount');
1963         createSimpleUpdateWatcher('mint_condition');
1964         createSimpleUpdateWatcher('opac_visible');
1965         createSimpleUpdateWatcher('ref');
1966
1967         $scope.saveCompletedCopies = function (and_exit) {
1968             var cnHash = {};
1969             var perCnCopies = {};
1970             angular.forEach( $scope.completed_copies, function (cp) {
1971                 var cn = cp.call_number();
1972                 var cn_cps = cp.call_number().copies();
1973                 cp.call_number().copies([]);
1974                 var cn_id = cp.call_number().id();
1975                 cp.call_number(cn_id); // prevent loops in JSON-ification
1976                 if (!cnHash[cn_id]) {
1977                     cnHash[cn_id] = egCore.idl.Clone(cn);
1978                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1979                 } else {
1980                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1981                 }
1982                 cp.call_number(cn); // put the data back
1983                 cp.call_number().copies(cn_cps);
1984                 if (typeof cnHash[cn_id].prefix() == 'object')
1985                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1986                 if (typeof cnHash[cn_id].suffix() == 'object')
1987                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1988             });
1989
1990             if ($scope.only_vols) { // strip off copies when we're in vol-only mode
1991                 angular.forEach(cnHash, function (v, k) {
1992                     cnHash[k].copies([]);
1993                 });
1994             } else {
1995                 angular.forEach(perCnCopies, function (v, k) {
1996                     cnHash[k].copies(v);
1997                 });
1998             }
1999
2000             cnList = [];
2001             angular.forEach(cnHash, function (v, k) {
2002                 cnList.push(v);
2003             });
2004
2005             egNet.request(
2006                 'open-ils.cat',
2007                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
2008                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1, return_copy_ids : 1 }
2009             ).then(function(copy_ids) {
2010                 if (and_exit) {
2011                     $scope.dirty = false;
2012                     if ($scope.defaults.print_item_labels) {
2013                         egCore.net.request(
2014                             'open-ils.actor',
2015                             'open-ils.actor.anon_cache.set_value',
2016                             null, 'print-labels-these-copies', {
2017                                 copies : copy_ids
2018                             }
2019                         ).then(function(key) {
2020                             if (key) {
2021                                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
2022                                 $timeout(function() { $window.open(url, '_blank') }).then(
2023                                     function() { $timeout(function(){$window.close()}); }
2024                                 );
2025                             } else {
2026                                 alert('Could not create anonymous cache key!');
2027                             }
2028                         });
2029                     } else {
2030                         $timeout(function(){
2031                             if (typeof BroadcastChannel != 'undefined') {
2032                                 var bChannel = new BroadcastChannel("eg.holdings.update");
2033                                 var bre_ids = cnList && cnList.length > 0 ? cnList.map(function(cn){ return Number(cn.record()) }) : [];
2034                                 var cn_ids = cnList && cnList.length > 0 ? cnList.map(function(cn){ return cn.id() }) : [];
2035                                 bChannel.postMessage({
2036                                     copies : copy_ids,
2037                                     volumes: cn_ids,
2038                                     records: bre_ids
2039                                 });
2040                             }
2041
2042                             $window.close();
2043                         });
2044                     }
2045                 }
2046             });
2047         }
2048
2049         $scope.saveAndContinue = function () {
2050             $scope.saveCompletedCopies(false);
2051         }
2052
2053         $scope.workingSaveAndExit = function () {
2054             $scope.workingToComplete();
2055             $scope.saveAndExit();
2056         }
2057
2058         $scope.saveAndExit = function () {
2059             $scope.saveCompletedCopies(true);
2060         }
2061
2062     }
2063
2064     $scope.copy_notes_dialog = function(copy_list) {
2065         var default_pub = Boolean($scope.defaults.copy_notes_pub);
2066         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2067
2068         return $uibModal.open({
2069             templateUrl: './cat/volcopy/t_copy_notes',
2070             backdrop: 'static',
2071             animation: true,
2072             controller:
2073                    ['$scope','$uibModalInstance',
2074             function($scope , $uibModalInstance) {
2075                 $scope.focusNote = true;
2076                 $scope.note = {
2077                     creator : egCore.auth.user().id(),
2078                     title   : '',
2079                     value   : '',
2080                     pub     : default_pub,
2081                 };
2082
2083                 $scope.require_initials = false;
2084                 egCore.org.settings([
2085                     'ui.staff.require_initials.copy_notes'
2086                 ]).then(function(set) {
2087                     $scope.require_initials_ous = Boolean(set['ui.staff.require_initials.copy_notes']);
2088                 });
2089
2090                 $scope.are_initials_required = function() {
2091                   $scope.require_initials = $scope.require_initials_ous && ($scope.note.value.length > 0 || $scope.note.title.length > 0);
2092                 };
2093
2094                 $scope.$watch('note.value.length', $scope.are_initials_required);
2095                 $scope.$watch('note.title.length', $scope.are_initials_required);
2096
2097                 $scope.note_list = [];
2098                 if (copy_list.length == 1) {
2099                     $scope.note_list = copy_list[0].notes();
2100                 }
2101
2102                 $scope.ok = function(note) {
2103
2104                     if (note.value.length > 0 || note.title.length > 0) {
2105                         if ($scope.initials) {
2106                             note.value = egCore.strings.$replace(
2107                                 egCore.strings.COPY_NOTE_INITIALS, {
2108                                 value : note.value,
2109                                 initials : $scope.initials,
2110                                 ws_ou : egCore.org.get(
2111                                     egCore.auth.user().ws_ou()).shortname()
2112                             });
2113                         }
2114
2115                         angular.forEach(copy_list, function (cp) {
2116                             if (!angular.isArray(cp.notes())) cp.notes([]);
2117                             var n = new egCore.idl.acpn();
2118                             n.isnew(1);
2119                             n.creator(note.creator);
2120                             n.pub(note.pub ? 't' : 'f');
2121                             n.title(note.title);
2122                             n.value(note.value);
2123                             n.owning_copy(cp.id());
2124                             cp.notes().push( n );
2125                         });
2126                     }
2127
2128                     $uibModalInstance.close();
2129                 }
2130
2131                 $scope.cancel = function($event) {
2132                     $uibModalInstance.dismiss();
2133                     $event.preventDefault();
2134                 }
2135             }]
2136         });
2137     }
2138
2139     $scope.copy_tags_dialog = function(copy_list) {
2140         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2141
2142         return $uibModal.open({
2143             templateUrl: './cat/volcopy/t_copy_tags',
2144             backdrop: 'static',
2145             animation: true,
2146             controller:
2147                    ['$scope','$uibModalInstance',
2148             function($scope , $uibModalInstance) {
2149
2150                 $scope.tag_map = [];
2151                 var tag_hash = {};
2152                 var shared_tags = {};
2153                 angular.forEach(copy_list, function (cp) {
2154                     angular.forEach(cp.tags(), function(tag) {
2155                         if (!(tag.tag().id() in shared_tags)) {
2156                             shared_tags[tag.tag().id()] = 1;
2157                         } else {
2158                             shared_tags[tag.tag().id()]++;
2159                         }
2160                         if (!(tag.tag().id() in tag_hash)) {
2161                             tag_hash[tag.tag().id()] = tag;
2162                         }
2163                     });
2164                 });
2165                 angular.forEach(tag_hash, function(value, key) {
2166                     if (shared_tags[key] == copy_list.length) {
2167                         $scope.tag_map.push(value);
2168                     }
2169                 });
2170
2171                 $scope.tag_types = [];
2172                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
2173                     $scope.tag_types = list;
2174                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
2175                 });
2176
2177                 $scope.getTags = function(val) {
2178                     return egCore.pcrud.search('acpt',
2179                         { 
2180                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
2181                             label : { 'startwith' : {
2182                                         transform: 'evergreen.lowercase',
2183                                         value : [ 'evergreen.lowercase', val ]
2184                                     }},
2185                             tag_type : $scope.tag_type
2186                         },
2187                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
2188                     ).then(function(list) {
2189                         return list.map(function(item) {
2190                             return item.label() + " (" + egCore.org.get(item.owner()).shortname() + ")";
2191                         });
2192                     });
2193                 }
2194
2195                 $scope.addTag = function() {
2196                     var tagLabel = $scope.selectedLabel;
2197                     // clear the typeahead
2198                     $scope.selectedLabel = "";
2199
2200                     // first, check tags already associated with the copy
2201                     var foundMatch = false;
2202                     angular.forEach($scope.tag_map, function(tag) {
2203                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
2204                             foundMatch = true;
2205                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
2206                         }
2207                     });
2208                     if (!foundMatch) {
2209                         egCore.pcrud.search('acpt',
2210                             { 
2211                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
2212                                 label : tagLabel,
2213                                 tag_type : $scope.tag_type
2214                             },
2215                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
2216                         ).then(function(list) {
2217                             if (list.length > 0) {
2218                                 var newMap = new egCore.idl.acptcm();
2219                                 newMap.isnew(1);
2220                                 newMap.copy(copy_list[0].id());
2221                                 newMap.tag(egCore.idl.Clone(list[0]));
2222                                 $scope.tag_map.push(newMap);
2223                             } else {
2224                                 var newTag = new egCore.idl.acpt();
2225                                 newTag.isnew(1);
2226                                 newTag.owner(egCore.auth.user().ws_ou());
2227                                 newTag.label(tagLabel);
2228                                 newTag.pub('t');
2229                                 newTag.tag_type($scope.tag_type);
2230
2231                                 var newMap = new egCore.idl.acptcm();
2232                                 newMap.isnew(1);
2233                                 newMap.copy(copy_list[0].id());
2234                                 newMap.tag(newTag);
2235                                 $scope.tag_map.push(newMap);
2236                             }
2237                         });
2238                     }
2239                 }
2240
2241                 $scope.ok = function(note) {
2242                     // in the multi-item case, this works OK for
2243                     // adding new maps to existing tags, but doesn't handle
2244                     // all possibilities
2245                     angular.forEach(copy_list, function (cp) {
2246                         cp.tags($scope.tag_map);
2247                     });
2248                     $uibModalInstance.close();
2249                 }
2250
2251                 $scope.cancel = function($event) {
2252                     $uibModalInstance.dismiss();
2253                     $event.preventDefault();
2254                 }
2255             }]
2256         });
2257     }
2258
2259     $scope.copy_alerts_dialog = function(copy_list) {
2260         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2261
2262         return $uibModal.open({
2263             templateUrl: './cat/volcopy/t_copy_alerts',
2264             animation: true,
2265             controller:
2266                    ['$scope','$uibModalInstance',
2267             function($scope , $uibModalInstance) {
2268
2269                 itemSvc.get_copy_alert_types().then(function(ccat) {
2270                     $scope.alert_types = ccat;
2271                 });
2272
2273                 $scope.focusNote = true;
2274                 $scope.copy_alert = {
2275                     create_staff : egCore.auth.user().id(),
2276                     note         : '',
2277                     temp         : false
2278                 };
2279
2280                 egCore.hatch.getItem('cat.copy.alerts.last_type').then(function(t) {
2281                     if (t) $scope.copy_alert.alert_type = t;
2282                 });
2283
2284                 if (copy_list.length == 1) {
2285                     $scope.copy_alert_list = copy_list[0].copy_alerts();
2286                 }
2287
2288                 $scope.ok = function(copy_alert) {
2289
2290                     if (typeof(copy_alert.note) != 'undefined' &&
2291                         copy_alert.note != '') {
2292                         angular.forEach(copy_list, function (cp) {
2293                             var a = new egCore.idl.aca();
2294                             a.isnew(1);
2295                             a.create_staff(copy_alert.create_staff);
2296                             a.note(copy_alert.note);
2297                             a.temp(copy_alert.temp ? 't' : 'f');
2298                             a.copy(cp.id());
2299                             a.ack_time(null);
2300                             a.alert_type(
2301                                 $scope.alert_types.filter(function(at) {
2302                                     return at.id() == copy_alert.alert_type;
2303                                 })[0]
2304                             );
2305                             cp.copy_alerts().push( a );
2306                         });
2307
2308                         if (copy_alert.alert_type) {
2309                             egCore.hatch.setItem(
2310                                 'cat.copy.alerts.last_type',
2311                                 copy_alert.alert_type
2312                             );
2313                         }
2314
2315                     }
2316
2317                     $uibModalInstance.close();
2318                 }
2319
2320                 $scope.cancel = function($event) {
2321                     $uibModalInstance.dismiss();
2322                     $event.preventDefault();
2323                 }
2324             }]
2325         });
2326     }
2327
2328 }])
2329
2330 .directive("egVolTemplate", function () {
2331     return {
2332         restrict: 'E',
2333         replace: true,
2334         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
2335         scope: {
2336             editTemplates: '=',
2337         },
2338         controller : ['$scope','$window','itemSvc','egCore','ngToast','$uibModal',
2339             function ( $scope , $window , itemSvc , egCore , ngToast , $uibModal) {
2340
2341                 $scope.i18n = egCore.i18n;
2342
2343                 $scope.defaults = { // If defaults are not set at all, allow everything
2344                     barcode_checkdigit : false,
2345                     auto_gen_barcode : false,
2346                     statcats : true,
2347                     copy_notes : true,
2348                     copy_tags : true,
2349                     copy_alerts : true,
2350                     attributes : {
2351                         status : true,
2352                         loan_duration : true,
2353                         fine_level : true,
2354                         cost : true,
2355                         alerts : true,
2356                         deposit : true,
2357                         deposit_amount : true,
2358                         opac_visible : true,
2359                         price : true,
2360                         circulate : true,
2361                         mint_condition : true,
2362                         circ_lib : true,
2363                         ref : true,
2364                         circ_modifier : true,
2365                         circ_as_type : true,
2366                         location : true,
2367                         holdable : true,
2368                         age_protect : true,
2369                         floating : true
2370                     }
2371                 };
2372
2373                 $scope.fetchDefaults = function () {
2374                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
2375                         if (t) {
2376                             $scope.defaults = t;
2377                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
2378                             if (
2379                                     typeof $scope.defaults.statcat_filter == 'object' &&
2380                                     Object.keys($scope.defaults.statcat_filter).length > 0
2381                                 ) {
2382                                 // want fieldmapper object here...
2383                                 $scope.defaults.statcat_filter =
2384                                     egCore.idl.Clone($scope.defaults.statcat_filter);
2385                                 // ... and ID here
2386                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
2387                             }
2388                         }
2389                     });
2390                 }
2391                 $scope.fetchDefaults();
2392
2393                 $scope.dirty = false;
2394                 $scope.$watch('dirty',
2395                     function(newVal, oldVal) {
2396                         if (newVal && newVal != oldVal) {
2397                             $($window).on('beforeunload.template', function(){
2398                                 return 'There is unsaved template data!'
2399                             });
2400                         } else {
2401                             $($window).off('beforeunload.template');
2402                         }
2403                     }
2404                 );
2405
2406                 $scope.template_controls = true;
2407
2408                 $scope.fetchTemplates = function () {
2409                     itemSvc.get_acp_templates().then(function(t) {
2410                         if (t) {
2411                             $scope.templates = t;
2412                             $scope.template_name_list = Object.keys(t).sort();
2413                         }
2414                     });
2415                 }
2416                 $scope.fetchTemplates();
2417             
2418                 $scope.applyTemplate = function (n) {
2419                     angular.forEach($scope.templates[n], function (v,k) {
2420                         if (k == 'circ_lib') {
2421                             $scope.working[k] = egCore.org.get(v);
2422                         } else if (angular.isArray(v) || !angular.isObject(v)) {
2423                             $scope.working[k] = angular.copy(v);
2424                         } else {
2425                             angular.forEach(v, function (sv,sk) {
2426                                 if (!(k in $scope.working))
2427                                     $scope.working[k] = {};
2428                                 $scope.working[k][sk] = angular.copy(sv);
2429                             });
2430                         }
2431                     });
2432                     $scope.template_name = '';
2433                 }
2434
2435                 $scope.deleteTemplate = function (n) {
2436                     if (n) {
2437                         delete $scope.templates[n]
2438                         $scope.template_name_list = Object.keys($scope.templates).sort();
2439                         $scope.template_name = '';
2440                         itemSvc.save_acp_templates($scope.templates);
2441                         $scope.$parent.fetchTemplates();
2442                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
2443                     }
2444                 }
2445
2446                 $scope.saveTemplate = function (n) {
2447                     if (n) {
2448                         var tmpl = {};
2449             
2450                         angular.forEach($scope.working, function (v,k) {
2451                             if (angular.isObject(v)) { // we'll use the pkey
2452                                 if (v.id) v = v.id();
2453                                 else if (v.code) v = v.code();
2454                                 else v = angular.copy(v); // Should only be statcats and callnumbers currently
2455                             }
2456             
2457                             tmpl[k] = v;
2458                         });
2459             
2460                         $scope.templates[n] = tmpl;
2461                         $scope.template_name_list = Object.keys($scope.templates).sort();
2462             
2463                         itemSvc.save_acp_templates($scope.templates);
2464                         $scope.$parent.fetchTemplates();
2465
2466                         $scope.dirty = false;
2467                     } else {
2468                         // save all templates, as we might do after an import
2469                         itemSvc.save_acp_templates($scope.templates);
2470                         $scope.$parent.fetchTemplates();
2471                     }
2472                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
2473                 }
2474
2475                 $scope.templates = {};
2476                 $scope.imported_templates = { data : '' };
2477                 $scope.template_name = '';
2478                 $scope.template_name_list = [];
2479
2480                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
2481                     if (newVal && newVal != oldVal) {
2482                         try {
2483                             var newTemplates = JSON.parse(newVal);
2484                             if (!Object.keys(newTemplates).length) return;
2485                             angular.forEach(Object.keys(newTemplates), function (k) {
2486                                 $scope.templates[k] = newTemplates[k];
2487                             });
2488                             itemSvc.save_acp_templates($scope.templates);
2489                             $scope.fetchTemplates();
2490                         } catch (E) {
2491                             console.log('tried to import an invalid copy template file');
2492                         }
2493                     }
2494                 });
2495
2496                 $scope.tracker = function (x,f) { if (x) return x[f]() };
2497                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
2498                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
2499             
2500                 $scope.orgById = function (id) { return egCore.org.get(id) }
2501                 $scope.statusById = function (id) {
2502                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
2503                 }
2504                 $scope.locationById = function (id) {
2505                     return $scope.location_cache[''+id];
2506                 }
2507             
2508                 createSimpleUpdateWatcher = function (field) {
2509                     $scope.$watch('working.' + field, function () {
2510                         var newval = $scope.working[field];
2511             
2512                         if (typeof newval != 'undefined') {
2513                             $scope.dirty = true;
2514                             if (angular.isObject(newval)) { // we'll use the pkey
2515                                 if (newval.id) $scope.working[field] = newval.id();
2516                                 else if (newval.code) $scope.working[field] = newval.code();
2517                             }
2518             
2519                             if (""+newval == "" || newval == null) {
2520                                 $scope.working[field] = undefined;
2521                             }
2522             
2523                         }
2524                     });
2525                 }
2526             
2527                 $scope.working = {
2528                     copy_notes: [],
2529                     copy_alerts: [],
2530                     statcats: {},
2531                     statcat_filter: undefined
2532                 };
2533             
2534                 $scope.statcat_visible = function (sc_owner) {
2535                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
2536                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
2537                         if ($scope.working.statcat_filter == ancestor_org.id())
2538                             visible = true;
2539                     });
2540                     return visible;
2541                 }
2542
2543                 createStatcatUpdateWatcher = function (id) {
2544                     return $scope.$watch('working.statcats[' + id + ']', function () {
2545                         if ($scope.working.statcats) {
2546                             var newval = $scope.working.statcats[id];
2547                 
2548                             if (typeof newval != 'undefined') {
2549                                 $scope.dirty = true;
2550                                 if (angular.isObject(newval)) { // we'll use the pkey
2551                                     newval = newval.id();
2552                                 }
2553                 
2554                                 if (""+newval == "" || newval == null) {
2555                                     $scope.working.statcats[id] = undefined;
2556                                     newval = null;
2557                                 }
2558                 
2559                             }
2560                         }
2561                     });
2562                 }
2563
2564                 $scope.clearWorking = function () {
2565                     angular.forEach($scope.working, function (v,k,o) {
2566                         $scope.working.MultiMap[k] = [];
2567                         if (!angular.isObject(v)) {
2568                             if (typeof v != 'undefined')
2569                                 $scope.working[k] = undefined;
2570                         } else if (k != 'circ_lib') {
2571                             angular.forEach(v, function (sv,sk) {
2572                                 $scope.working[k][sk] = undefined;
2573                             });
2574                         }
2575                     });
2576                     $scope.working.circ_lib = undefined; // special
2577                     $scope.dirty = false;
2578                 }
2579
2580                 $scope.working = {};
2581                 $scope.location_orgs = [];
2582                 $scope.location_cache = {};
2583             
2584                 $scope.location_list = [];
2585                 itemSvc.get_locations_by_org(
2586                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2587                 ).then(function(list){
2588                     $scope.location_list = list;
2589                 });
2590                 createSimpleUpdateWatcher('location');
2591
2592                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2593
2594                 $scope.statcats = [];
2595                 itemSvc.get_statcats(
2596                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2597                 ).then(function(list){
2598                     $scope.statcats = list;
2599                     angular.forEach($scope.statcats, function (s) {
2600
2601                         if (!$scope.working)
2602                             $scope.working = { statcats: {}, statcat_filter: undefined};
2603                         if (!$scope.working.statcats)
2604                             $scope.working.statcats = {};
2605
2606                         $scope.working.statcats[s.id()] = undefined;
2607                         createStatcatUpdateWatcher(s.id());
2608                     });
2609                 });
2610
2611                 $scope.copy_notes_dialog = function() {
2612                     var default_pub = Boolean($scope.defaults.copy_notes_pub);
2613                     var working = $scope.working;
2614             
2615                     return $uibModal.open({
2616                         templateUrl: './cat/volcopy/t_copy_notes',
2617                         animation: true,
2618                         controller:
2619                             ['$scope','$uibModalInstance',
2620                         function($scope , $uibModalInstance) {
2621                             $scope.focusNote = true;
2622                             $scope.note = {
2623                                 title   : '',
2624                                 value   : '',
2625                                 pub     : default_pub,
2626                             };
2627
2628                             $scope.require_initials = false;
2629                             egCore.org.settings([
2630                                 'ui.staff.require_initials.copy_notes'
2631                             ]).then(function(set) {
2632                                 $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
2633                             });
2634
2635                             $scope.note_list = [];
2636                             angular.forEach(working.copy_notes, function(note) {
2637                                 var acpn = egCore.idl.fromHash('acpn', note);
2638                                 $scope.note_list.push(acpn);
2639                             });
2640
2641                             $scope.ok = function(note) {
2642
2643                                 if (!working.copy_notes) {
2644                                     working.copy_notes = [];
2645                                 }
2646
2647                                 // clear slate
2648                                 working.copy_notes.length = 0;
2649                                 angular.forEach($scope.note_list, function(existing_note) {
2650                                     if (!existing_note.isdeleted()) {
2651                                         working.copy_notes.push({
2652                                             pub : existing_note.pub() ? 't' : 'f',
2653                                             title : existing_note.title(),
2654                                             value : existing_note.value()
2655                                         });
2656                                     }
2657                                 });
2658
2659                                 // add new note, if any
2660                                 if (note.initials) note.value += ' [' + note.initials + ']';
2661                                 note.pub = note.pub ? 't' : 'f';
2662                                 if (note.title.length && note.value.length) {
2663                                     working.copy_notes.push(note);
2664                                 }
2665
2666                                 $uibModalInstance.close();
2667                             }
2668
2669                             $scope.cancel = function($event) {
2670                                 $uibModalInstance.dismiss();
2671                                 $event.preventDefault();
2672                             }
2673                         }]
2674                     });
2675                 }
2676             
2677                 $scope.copy_alerts_dialog = function() {
2678                     var working = $scope.working;
2679
2680                     return $uibModal.open({
2681                         templateUrl: './cat/volcopy/t_copy_alerts',
2682                         animation: true,
2683                         controller:
2684                             ['$scope','$uibModalInstance',
2685                         function($scope , $uibModalInstance) {
2686
2687                             itemSvc.get_copy_alert_types().then(function(ccat) {
2688                                 var ccat_map = {};
2689                                 $scope.alert_types = ccat;
2690                                 angular.forEach(ccat, function(t) {
2691                                     ccat_map[t.id()] = t;
2692                                 });
2693                                 $scope.copy_alert_list = [];
2694                                 angular.forEach(working.copy_alerts, function (alrt) {
2695                                     var aca = egCore.idl.fromHash('aca', alrt);
2696                                     aca.alert_type(ccat_map[alrt.alert_type]);
2697                                     aca.ack_time(null);
2698                                     $scope.copy_alert_list.push(aca);
2699                                 });
2700                             });
2701
2702                             $scope.focusNote = true;
2703                             $scope.copy_alert = {
2704                                 note         : '',
2705                                 temp         : false
2706                             };
2707
2708                             $scope.ok = function(copy_alert) {
2709             
2710                                 if (!working.copy_alerts) {
2711                                     working.copy_alerts = [];
2712                                 }
2713                                 // clear slate
2714                                 working.copy_alerts.length = 0;
2715
2716                                 angular.forEach($scope.copy_alert_list, function(alrt) {
2717                                     if (alrt.ack_time() == null) {
2718                                         working.copy_alerts.push({
2719                                             note : alrt.note(),
2720                                             temp : alrt.temp(),
2721                                             alert_type : alrt.alert_type().id()
2722                                         });
2723                                     }
2724                                 });
2725
2726                                 if (typeof(copy_alert.note) != 'undefined' &&
2727                                     copy_alert.note != '') {
2728                                     working.copy_alerts.push({
2729                                         note : copy_alert.note,
2730                                         temp : copy_alert.temp ? 't' : 'f',
2731                                         alert_type : copy_alert.alert_type
2732                                     });
2733                                 }
2734
2735                                 $uibModalInstance.close();
2736                             }
2737
2738                             $scope.cancel = function($event) {
2739                                 $uibModalInstance.dismiss();
2740                                 $event.preventDefault();
2741                             }
2742                         }]
2743                     });
2744                 }
2745
2746                 $scope.status_list = [];
2747                 itemSvc.get_magic_statuses().then(function(list){
2748                     $scope.magic_status_list = list;
2749                 });
2750                 itemSvc.get_statuses().then(function(list){
2751                     $scope.status_list = list;
2752                 });
2753                 createSimpleUpdateWatcher('status');
2754             
2755                 $scope.circ_modifier_list = [];
2756                 itemSvc.get_circ_mods().then(function(list){
2757                     $scope.circ_modifier_list = list;
2758                 });
2759                 createSimpleUpdateWatcher('circ_modifier');
2760             
2761                 $scope.circ_type_list = [];
2762                 itemSvc.get_circ_types().then(function(list){
2763                     $scope.circ_type_list = list;
2764                 });
2765                 createSimpleUpdateWatcher('circ_as_type');
2766             
2767                 $scope.age_protect_list = [];
2768                 itemSvc.get_age_protects().then(function(list){
2769                     $scope.age_protect_list = list;
2770                 });
2771                 createSimpleUpdateWatcher('age_protect');
2772
2773                 $scope.floating_list = [];
2774                 itemSvc.get_floating_groups().then(function(list){
2775                     $scope.floating_list = list;
2776                 });
2777                 createSimpleUpdateWatcher('floating');
2778
2779                 createSimpleUpdateWatcher('circulate');
2780                 createSimpleUpdateWatcher('holdable');
2781                 createSimpleUpdateWatcher('fine_level');
2782                 createSimpleUpdateWatcher('loan_duration');
2783                 createSimpleUpdateWatcher('cost');
2784                 createSimpleUpdateWatcher('deposit');
2785                 createSimpleUpdateWatcher('deposit_amount');
2786                 createSimpleUpdateWatcher('mint_condition');
2787                 createSimpleUpdateWatcher('opac_visible');
2788                 createSimpleUpdateWatcher('ref');
2789
2790                 $scope.suffix_list = [];
2791                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2792                     $scope.suffix_list = list;
2793                 });
2794
2795                 $scope.prefix_list = [];
2796                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2797                     $scope.prefix_list = list;
2798                 });
2799
2800                 $scope.classification_list = [];
2801                 itemSvc.get_classifications().then(function(list){
2802                     $scope.classification_list = list;
2803                 });
2804
2805                 createSimpleUpdateWatcher('working.callnumber.classification');
2806                 createSimpleUpdateWatcher('working.callnumber.prefix');
2807                 createSimpleUpdateWatcher('working.callnumber.suffix');
2808             }
2809         ]
2810     }
2811 })
2812
2813