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