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