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