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