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