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