501a9c1785b5f8e1a6104d962b28b867b2a388e5
[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', 'creator', 'editor'],
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.changed_fields = [];
1156
1157     $scope.completeToWorking = function () {
1158         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
1159             angular.forEach( $scope.completed_copies, function (w, i) {
1160                 if (c === w)
1161                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
1162             });
1163         });
1164
1165         return true;
1166     }
1167
1168     createSimpleUpdateWatcher = function (field,exclude_copies_with_one_of_these_values) {
1169         return $scope.$watch('working.' + field, function () {
1170             var newval = $scope.working[field];
1171
1172             if (typeof newval != 'undefined') {
1173                 delete $scope.working.MultiMap[field];
1174                 if (angular.isObject(newval)) { // we'll use the pkey
1175                     if (newval.id) newval = newval.id();
1176                     else if (newval.code) newval = newval.code();
1177                 }
1178
1179                 if (""+newval == "" || newval == null) {
1180                     $scope.working[field] = undefined;
1181                     newval = null;
1182                 }
1183
1184                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1185                     angular.forEach(
1186                         $scope.workingGridControls.selectedItems(),
1187                         function (cp) {
1188                             if (exclude_copies_with_one_of_these_values
1189                                 && exclude_copies_with_one_of_these_values.indexOf(cp[field](),0) > -1) {
1190                                 return;
1191                             }
1192                             if (cp[field]() !== newval) {
1193                                 $scope.changed_fields[cp.$$hashKey+field] = true;
1194                                 cp[field](newval);
1195                                 cp.ischanged(1);
1196                                 $scope.dirty = true;
1197                             }
1198                         }
1199                     );
1200                 }
1201             }
1202         });
1203     }
1204
1205     // determine if any of the selected copies have had changed their value for this field:
1206     $scope.field_changed = function (field){
1207         // if objects controlling selection don't exist, assume the fields haven't changed
1208         if(!$scope.workingGridControls || !$scope.workingGridControls.selectedItems){ return false; }
1209         var selected = $scope.workingGridControls.selectedItems();
1210         return selected.reduce((acc, cp) => acc || $scope.changed_fields[cp.$$hashKey+field], false);
1211     };
1212
1213     $scope.working = {
1214         MultiMap: {},
1215         statcats: {},
1216         statcats_multi: {},
1217         statcat_filter: undefined
1218     };
1219
1220     // Returns true if we are editing multiple copies and at least
1221     // one field contains multiple values.
1222     $scope.hasMulti = function() {
1223         var keys = Object.keys($scope.working.MultiMap);
1224         // for-loop for shortcut exit
1225         for (var i = 0; i < keys.length; i++) {
1226             if ($scope.working.MultiMap[keys[i]] &&
1227                 $scope.working.MultiMap[keys[i]].length > 1) {
1228                 return true;
1229             }
1230         }
1231         return false;
1232     }
1233
1234     $scope.copyAlertUpdate = function (alerts) {
1235         if (!$scope.in_item_select &&
1236             $scope.workingGridControls &&
1237             $scope.workingGridControls.selectedItems) {
1238             itemSvc.get_copy_alert_types().then(function(ccat) {
1239                 var ccat_map = {};
1240                 $scope.alert_types = ccat;
1241                 angular.forEach(ccat, function(t) {
1242                     ccat_map[t.id()] = t;
1243                 });
1244                 angular.forEach(
1245                     $scope.workingGridControls.selectedItems(),
1246                     function (cp) {
1247                         if (!angular.isArray(cp.copy_alerts())) cp.copy_alerts([]);
1248                         $scope.dirty = true;
1249                         angular.forEach(alerts, function(alrt) {
1250                             var a = egCore.idl.fromHash('aca', alrt);
1251                             a.isnew(1);
1252                             a.create_staff(egCore.auth.user().id());
1253                             a.alert_type(ccat_map[a.alert_type()]);
1254                             a.ack_time(null);
1255                             a.copy(cp.id());
1256                             cp.copy_alerts().push( a );
1257                         });
1258                         cp.ischanged(1);
1259                     }
1260                 );
1261             });
1262         }
1263     };
1264
1265     $scope.copyNoteUpdate = function (notes) {
1266         if (!$scope.in_item_select &&
1267             $scope.workingGridControls &&
1268             $scope.workingGridControls.selectedItems) {
1269             angular.forEach(
1270                 $scope.workingGridControls.selectedItems(),
1271                 function (cp) {
1272                     if (!angular.isArray(cp.notes())) cp.notes([]);
1273                     $scope.dirty = true;
1274                     angular.forEach(notes, function(note) {
1275                         var n = egCore.idl.fromHash('acpn', note);
1276                         n.isnew(1);
1277                         n.creator(egCore.auth.user().id());
1278                         n.owning_copy(cp.id());
1279                         cp.notes().push( n );
1280                     });
1281                     cp.ischanged(1);
1282                 }
1283             );
1284
1285         }
1286     }
1287
1288     $scope.statcatUpdate = function (id) {
1289         var newval = $scope.working.statcats[id];
1290
1291         if (typeof newval != 'undefined') {
1292             if (angular.isObject(newval)) { // we'll use the pkey
1293                 newval = newval.id();
1294             }
1295     
1296             if (""+newval == "" || newval == null) {
1297                 $scope.working.statcats[id] = undefined;
1298                 newval = null;
1299             }
1300     
1301             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1302                 angular.forEach(
1303                     $scope.workingGridControls.selectedItems(),
1304                     function (cp) {
1305                         $scope.dirty = true;
1306
1307                         cp.stat_cat_entries(
1308                             angular.forEach( cp.stat_cat_entries(), function (e) {
1309                                 if (e.stat_cat() == id) { // mark deleted
1310                                     e.isdeleted(1);
1311                                 }
1312                             })
1313                         );
1314     
1315                         if (newval) {
1316                             var e = new egCore.idl.asce();
1317                             e.isnew( 1 );
1318                             e.stat_cat( id );
1319                             e.id(newval);
1320
1321                             cp.stat_cat_entries(
1322                                 cp.stat_cat_entries() ?
1323                                     cp.stat_cat_entries().concat([ e ]) :
1324                                     [ e ]
1325                             );
1326
1327                         }
1328
1329                         // trim out all deleted ones; the API used to
1330                         // do the update doesn't actually consult
1331                         // isdeleted for stat cat entries
1332                         if (cp.stat_cat_entries()) {
1333                             cp.stat_cat_entries(
1334                                 cp.stat_cat_entries().filter(function (e) {
1335                                     return !Boolean(e.isdeleted());
1336                                 })
1337                             );
1338                         }
1339    
1340                         cp.ischanged(1);
1341                     }
1342                 );
1343             }
1344         }
1345     }
1346
1347     var dataKey = $routeParams.dataKey;
1348     console.debug('dataKey: ' + dataKey);
1349
1350     if ((dataKey && dataKey.length > 0) || $scope.edit_templates) {
1351
1352         $scope.templates = {};
1353         $scope.template_name = '';
1354         $scope.template_name_list = [];
1355
1356         $scope.fetchTemplates = function () {
1357             itemSvc.get_acp_templates().then(function(t) {
1358                 if (t) {
1359                     $scope.templates = t;
1360                     $scope.template_name_list = Object.keys(t).sort();
1361                 }
1362             });
1363             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
1364                 if (t) $scope.template_name = t;
1365             });
1366         }
1367         $scope.fetchTemplates();
1368
1369         $scope.applyTemplate = function (n) {
1370             angular.forEach($scope.templates[n], function (v,k) {
1371                 if (k == 'circ_lib') {
1372                     $scope.working[k] = egCore.org.get(v);
1373                 } else if (k == 'copy_notes' && v.length) {
1374                     $scope.copyNoteUpdate(v);
1375                 } else if (k == 'copy_alerts' && v.length) {
1376                     $scope.copyAlertUpdate(v);
1377                 } else if (!angular.isObject(v)) {
1378                     $scope.working[k] = angular.copy(v);
1379                 } else {
1380                     angular.forEach(v, function (sv,sk) {
1381                         if (k == 'callnumber') {
1382                             angular.forEach(v, function (cnv,cnk) {
1383                                 $scope.batch[cnk] = cnv;
1384                             });
1385                             $scope.applyBatchCNValues();
1386                         } else {
1387                             $scope.working[k][sk] = angular.copy(sv);
1388                             if (k == 'statcats') $scope.statcatUpdate(sk);
1389                         }
1390                     });
1391                 }
1392                 delete $scope.working.MultiMap[k];
1393             });
1394             egCore.hatch.setItem('cat.copy.last_template', n);
1395         }
1396
1397         $scope.copytab = 'working';
1398         $scope.tab = 'edit';
1399         $scope.summaryRecord = null;
1400         $scope.record_id = null;
1401         $scope.data = {};
1402         $scope.completed_copies = [];
1403         $scope.location_orgs = [];
1404         $scope.location_cache = {};
1405         $scope.statcats = [];
1406         if (!$scope.batch) $scope.batch = {};
1407
1408         $scope.applyBatchCNValues = function () {
1409             if ($scope.data.tree) {
1410                 angular.forEach($scope.data.tree, function(cn_hash) {
1411                     angular.forEach(cn_hash, function(copies) {
1412                         angular.forEach(copies, function(cp) {
1413                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
1414                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
1415                                 cp.call_number().label_class(label_class);
1416                                 cp.call_number().ischanged(1);
1417                                 $scope.dirty = true;
1418                             }
1419                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
1420                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
1421                                 cp.call_number().prefix(prefix);
1422                                 cp.call_number().ischanged(1);
1423                                 $scope.dirty = true;
1424                             }
1425                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
1426                                 cp.call_number().label($scope.batch.label);
1427                                 cp.call_number().ischanged(1);
1428                                 $scope.dirty = true;
1429                             }
1430                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
1431                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
1432                                 cp.call_number().suffix(suffix);
1433                                 cp.call_number().ischanged(1);
1434                                 $scope.dirty = true;
1435                             }
1436                         });
1437                     });
1438                 });
1439             }
1440         }
1441
1442         $scope.clearWorking = function () {
1443             angular.forEach($scope.working, function (v,k,o) {
1444                 if (k != 'MultiMap') $scope.working.MultiMap[k] = [];
1445                 if (!angular.isObject(v)) {
1446                     if (typeof v != 'undefined')
1447                         $scope.working[k] = undefined;
1448                 } else if (k != 'circ_lib' && k != 'MultiMap') {
1449                     angular.forEach(v, function (sv,sk) {
1450                         if (typeof v != 'undefined')
1451                             $scope.working[k][sk] = undefined;
1452                     });
1453                 }
1454             });
1455             $scope.working.circ_lib = undefined; // special
1456         }
1457
1458         $scope.completedGridDataProvider = egGridDataProvider.instance({
1459             get : function(offset, count) {
1460                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1461                 return this.arrayNotifier($scope.completed_copies, offset, count);
1462             }
1463         });
1464
1465         $scope.completedGridControls = {};
1466
1467         $scope.workingGridDataProvider = egGridDataProvider.instance({
1468             get : function(offset, count) {
1469                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1470                 return this.arrayNotifier(itemSvc.copies, offset, count);
1471             }
1472         });
1473
1474         $scope.workingGridControls = {};
1475         $scope.add_vols_copies = false;
1476         $scope.is_fast_add = false;
1477
1478         // Generate some functions for selecting items by column value in the working grid
1479         angular.forEach(
1480             ['circulate','status','circ_lib','ref','location','opac_visible','circ_modifier','price',
1481              'loan_duration','cost','circ_as_type','deposit','holdable','deposit_amount','age_protect',
1482              'mint_condition','fine_level','floating'],
1483             function (field) {
1484                 $scope['select_by_' + field] = function (x) {
1485                     $scope.workingGridControls.selectItemsByValue(field,x);
1486                 }
1487             }
1488         );
1489
1490         var truthy = /^t|1/;
1491         $scope.labelYesNo = function (x) {
1492             return truthy.test(x) ? egCore.strings.YES : egCore.strings.NO;
1493         }
1494
1495         $scope.orgShortname = function (x) {
1496             return egCore.org.get(x).shortname();
1497         }
1498
1499         $scope.statusName = function (x) {
1500             var s = $scope.status_list.filter(function(y) {
1501                 return y.id() == x;
1502             });
1503
1504             return s[0].name();
1505         }
1506
1507         $scope.locationName = function (x) {
1508             var s = $scope.location_list.filter(function(y) {
1509                 return y.id() == x;
1510             });
1511
1512             return $scope.i18n.ou_qualified_location_name(s[0]);
1513         }
1514
1515         $scope.durationLabel = function (x) {
1516             return [egCore.strings.SHORT, egCore.strings.NORMAL, egCore.strings.EXTENDED][-1 + x]
1517         }
1518
1519         $scope.fineLabel = function (x) {
1520             return [egCore.strings.LOW, egCore.strings.NORMAL, egCore.strings.HIGH][-1 + x]
1521         }
1522
1523         $scope.circTypeValue = function (x) {
1524             if (x === null || x === undefined) return egCore.strings.UNSET;
1525             var s = $scope.circ_type_list.filter(function(y) {
1526                 return y.code() == x;
1527             });
1528
1529             return s[0].value();
1530         }
1531
1532         $scope.ageprotectName = function (x) {
1533             if (x === null || x === undefined) return egCore.strings.UNSET;
1534             var s = $scope.age_protect_list.filter(function(y) {
1535                 return y.id() == x;
1536             });
1537
1538             return s[0].name();
1539         }
1540
1541         $scope.floatingName = function (x) {
1542             if (x === null || x === undefined) return egCore.strings.UNSET;
1543             var s = $scope.floating_list.filter(function(y) {
1544                 return y.id() == x;
1545             });
1546
1547             return s[0].name();
1548         }
1549
1550         $scope.circmodName = function (x) {
1551             if (x === null || x === undefined) return egCore.strings.UNSET;
1552             var s = $scope.circ_modifier_list.filter(function(y) {
1553                 return y.code() == x;
1554             });
1555
1556             return s[0].name();
1557         }
1558
1559         egNet.request(
1560             'open-ils.actor',
1561             'open-ils.actor.anon_cache.get_value',
1562             dataKey, 'edit-these-copies'
1563         ).then(function (data) {
1564
1565             if (data) {
1566                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1567                 if (data.hide_copies) {
1568                     $scope.show_copies = false;
1569                     $scope.only_vols = true;
1570                 }
1571
1572                 $scope.record_id = data.record_id;
1573
1574                 // Fetch defaults 
1575                 $scope.fetchDefaults();
1576
1577                 function fetchRaw () {
1578                     if (!$scope.only_vols) $scope.dirty = true;
1579                     $scope.add_vols_copies = true;
1580
1581                     /* data.raw data structure looks like this:
1582                      * [{
1583                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1584                      *      owner      : $org, // optional, defaults to cn.owning_lib or ws_ou
1585                      *      label      : $cn_label, // optional, to supply a label on a new cn
1586                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1587                      *      fast_add   : boolean // optional, to specify whether this came
1588                      *                              in as a fast add
1589                      * },...]
1590                      * 
1591                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1592                      */
1593
1594                     var promises = [];
1595                     angular.forEach(
1596                         data.raw,
1597                         function (proto) {
1598                             if (proto.fast_add) $scope.is_fast_add = true;
1599                             if (proto.callnumber) {
1600                                 promises.push(egCore.pcrud.retrieve('acn', proto.callnumber)
1601                                 .then(function(cn) {
1602                                     var cp = new itemSvc.generateNewCopy(
1603                                         cn,
1604                                         proto.owner || cn.owning_lib(),
1605                                         $scope.is_fast_add,
1606                                         ((!$scope.only_vols) ? true : false)
1607                                     );
1608
1609                                     if (proto.barcode) {
1610                                         cp.barcode( proto.barcode );
1611                                         cp.empty_barcode = false;
1612                                     }
1613
1614                                     itemSvc.addCopy(cp)
1615                                 }));
1616                             } else {
1617                                 var cn = new egCore.idl.acn();
1618                                 cn.id( --itemSvc.new_cn_id );
1619                                 cn.isnew( true );
1620                                 cn.prefix( $scope.defaults.prefix || -1 );
1621                                 cn.suffix( $scope.defaults.suffix || -1 );
1622                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1623                                 cn.record( $scope.record_id );
1624                                 egCore.org.settings(
1625                                     ['cat.default_classification_scheme'],
1626                                     cn.owning_lib()
1627                                 ).then(function (val) {
1628                                     cn.label_class(
1629                                         $scope.defaults.classification ||
1630                                         val['cat.default_classification_scheme'] ||
1631                                         1
1632                                     );
1633                                     if (proto.label) {
1634                                         cn.label( proto.label );
1635                                     } else {
1636                                         egCore.net.request(
1637                                             'open-ils.cat',
1638                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1639                                             $scope.record_id,
1640                                             cn.label_class()
1641                                         ).then(function(cn_array) {
1642                                             if (cn_array.length > 0) {
1643                                                 for (var field in cn_array[0]) {
1644                                                     cn.label( cn_array[0][field] );
1645                                                     break;
1646                                                 }
1647                                             }
1648                                         });
1649                                     }
1650                                 });
1651
1652                                 // If we are adding an empty vol,
1653                                 // this is ultimately just a placeholder copy
1654                                 // which gets removed before saving.
1655                                 // TODO: consider ways to remove this
1656                                 // requirement
1657                                 var cp = new itemSvc.generateNewCopy(
1658                                     cn,
1659                                     proto.owner || cn.owning_lib(),
1660                                     $scope.is_fast_add,
1661                                     true
1662                                 );
1663
1664                                 if (proto.barcode) {
1665                                     cp.barcode( proto.barcode );
1666                                     cp.empty_barcode = false;
1667                                 }
1668
1669                                 itemSvc.addCopy(cp)
1670                             }
1671                         }
1672                     );
1673
1674                     angular.forEach(itemSvc.copies, function(c){
1675                         var cn = c.call_number();
1676                         var copy_id = c.id();
1677                         if (copy_id > 0){
1678                             cn.not_ephemeral = true;
1679                         }
1680                     });
1681
1682                     return $q.all(promises);
1683                 }
1684
1685                 if (data.copies && data.copies.length)
1686                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1687
1688                 return fetchRaw();
1689
1690             }
1691
1692         }).then( function() {
1693
1694             return itemSvc.fetch_locations(
1695                 itemSvc.copies.map(function(cp){
1696                     return cp.location();
1697                 }).filter(function(e,i,a){
1698                     return a.lastIndexOf(e) === i;
1699                 })
1700             ).then(function(list){
1701                 $scope.data = itemSvc;
1702                 $scope.location_list = list;
1703                 $scope.workingGridDataProvider.refresh();
1704             });
1705
1706         });
1707
1708         $scope.can_save = false;
1709         function check_saveable () {
1710             var can_save = true;
1711
1712             angular.forEach(
1713                 itemSvc.copies,
1714                 function (i) {
1715                     if (!$scope.only_vols) {
1716                         if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label) {
1717                             can_save = false;
1718                         }
1719                     } else if (i.call_number().empty_label) {
1720                         can_save = false;
1721                     }
1722                 }
1723             );
1724
1725             if (!$scope.only_vols && $scope.forms.myForm && $scope.forms.myForm.$invalid) {
1726                 can_save = false;
1727             }
1728
1729             $scope.can_save = can_save;
1730         }
1731
1732         $scope.disableSave = function () {
1733             check_saveable();
1734             return !$scope.can_save;
1735         }
1736
1737         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1738             var n;
1739             var yep = false;
1740             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1741                 if (n) return;
1742
1743                 if (lib == prev_lib) {
1744                     yep = true;
1745                     return;
1746                 }
1747
1748                 if (yep) n = lib;
1749             });
1750
1751             if (n) {
1752                 var first_cn = Object.keys($scope.data.tree[n])[0];
1753                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1754                 var el = $(next);
1755                 if (el) {
1756                     if (!itemSvc.currently_generating) el.focus();
1757                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1758                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1759                             el.focus();
1760                             el.val(bc);
1761                             el.trigger('change');
1762                         });
1763                     } else {
1764                         itemSvc.currently_generating = false;
1765                     }
1766                 }
1767             }
1768         }
1769
1770         $scope.in_item_select = false;
1771         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1772         $scope.handleItemSelect = function (item_list) {
1773             if (item_list && item_list.length > 0) {
1774                 $scope.in_item_select = true;
1775
1776                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1777
1778                     var value_hash = {};
1779                     var value_list = [];
1780                     angular.forEach(item_list, function (item) {
1781                         if (item[attr]) {
1782                             var v = item[attr]()
1783                             if (angular.isObject(v)) {
1784                                 if (v.id) v = v.id();
1785                                 else if (v.code) v = v.code();
1786                             }
1787                             value_list.push(v);
1788                             value_hash[v] = 1;
1789                         }
1790                     });
1791
1792                     $scope.working.MultiMap[attr] = value_list;
1793
1794                     if (Object.keys(value_hash).length == 1) {
1795                         if (attr == 'circ_lib') {
1796                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1797                         } else {
1798                             $scope.working[attr] = item_list[0][attr]();
1799                         }
1800                     } else {
1801                         $scope.working[attr] = undefined;
1802                     }
1803                 });
1804
1805                 angular.forEach($scope.statcats, function (sc) {
1806
1807                     var counter = -1;
1808                     var value_hash = {};
1809                     var none = false;
1810                     angular.forEach(item_list, function (item) {
1811                         if (item.stat_cat_entries()) {
1812                             if (item.stat_cat_entries().length > 0) {
1813                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1814                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1815                                 });
1816
1817                                 if (right_sc.length > 0) {
1818                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1819                                 } else {
1820                                     none = true;
1821                                 }
1822                             } else {
1823                                 none = true;
1824                             }
1825                         } else {
1826                             none = true;
1827                         }
1828                     });
1829
1830                     if (!none && Object.keys(value_hash).length == 1) {
1831                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1832                         $scope.working.statcats_multi[sc.id()] = false;
1833                     } else if (item_list.length > 1 && Object.keys(value_hash).length > 0) {
1834                         $scope.working.statcats[sc.id()] = undefined;
1835                         $scope.working.statcats_multi[sc.id()] = true;
1836                     } else {
1837                         $scope.working.statcats[sc.id()] = undefined;
1838                         $scope.working.statcats_multi[sc.id()] = false;
1839                     }
1840
1841                 });
1842
1843             } else {
1844                 $scope.clearWorking();
1845             }
1846
1847         }
1848
1849         $scope.$watch('data.copies.length', function () {
1850             if ($scope.data.copies) {
1851                 var base_orgs = $scope.data.copies.map(function(cp){
1852                     if (isNaN(cp.circ_lib())) return Number(cp.circ_lib().id());
1853                     return Number(cp.circ_lib());
1854                 }).concat(
1855                     $scope.data.copies.map(function(cp){
1856                         if (isNaN(cp.call_number().owning_lib())) return Number(cp.call_number().owning_lib().id());
1857                         return Number(cp.call_number().owning_lib());
1858                     })
1859                 ).concat(
1860                     [egCore.auth.user().ws_ou()]
1861                 ).filter(function(e,i,a){
1862                     return a.lastIndexOf(e) === i;
1863                 });
1864
1865                 var all_orgs = [];
1866                 angular.forEach(base_orgs, function(o) {
1867                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1868                 });
1869
1870                 var final_orgs = all_orgs.filter(function(e,i,a){
1871                     return a.lastIndexOf(e) === i;
1872                 }).sort(function(a, b){return a-b});
1873
1874                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1875                     $scope.location_orgs = final_orgs;
1876                     if ($scope.location_orgs.length) {
1877                         itemSvc.get_locations_by_org($scope.location_orgs).then(function(list){
1878                             angular.forEach(list, function(l) {
1879                                 $scope.location_cache[ ''+l.id() ] = l;
1880                             });
1881                             $scope.location_list = list;
1882                         }).then(function() {
1883                             $scope.statcat_filter_list = [];
1884                             angular.forEach($scope.location_orgs, function (o) {
1885                                 $scope.statcat_filter_list.push(egCore.org.get(o));
1886                             });
1887
1888                             itemSvc.get_statcats($scope.location_orgs).then(function(list){
1889                                 $scope.statcats = list;
1890                                 angular.forEach($scope.statcats, function (s) {
1891
1892                                     if (!$scope.working)
1893                                         $scope.working = { statcats_multi: {}, statcats: {}, statcat_filter: undefined};
1894                                     if (!$scope.working.statcats_multi)
1895                                         $scope.working.statcats_multi = {};
1896                                     if (!$scope.working.statcats)
1897                                         $scope.working.statcats = {};
1898
1899                                     if (!$scope.in_item_select) {
1900                                         $scope.working.statcats[s.id()] = undefined;
1901                                     }
1902                                     createStatcatUpdateWatcher(s.id());
1903                                 });
1904                                 $scope.in_item_select = false;
1905                                 // do a refresh here to work around a race
1906                                 // condition that can result in stat cats
1907                                 // not being selected.
1908                                 $scope.workingGridDataProvider.refresh();
1909                             });
1910                         });
1911                     }
1912                 } else {
1913                     $scope.workingGridDataProvider.refresh();
1914                 }
1915             }
1916         });
1917
1918         $scope.statcat_visible = function (sc_owner) {
1919             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1920             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1921                 if ($scope.working.statcat_filter == ancestor_org.id())
1922                     visible = true;
1923             });
1924             return visible;
1925         }
1926
1927         $scope.suffix_list = [];
1928         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1929             $scope.suffix_list = list;
1930         });
1931
1932         $scope.prefix_list = [];
1933         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1934             $scope.prefix_list = list;
1935         });
1936
1937         $scope.classification_list = [];
1938         itemSvc.get_classifications().then(function(list){
1939             $scope.classification_list = list;
1940         });
1941
1942         $scope.$watch('completed_copies.length', function () {
1943             $scope.completedGridDataProvider.refresh();
1944         });
1945
1946         $scope.location_list = [];
1947         createSimpleUpdateWatcher('location');
1948
1949         $scope.status_list = [];
1950         itemSvc.get_magic_statuses().then(function(list){
1951             $scope.magic_status_list = list;
1952             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1953         });
1954         itemSvc.get_statuses().then(function(list){
1955             $scope.status_list = list;
1956         });
1957
1958         $scope.circ_modifier_list = [];
1959         itemSvc.get_circ_mods().then(function(list){
1960             $scope.circ_modifier_list = list;
1961         });
1962         createSimpleUpdateWatcher('circ_modifier');
1963
1964         $scope.circ_type_list = [];
1965         itemSvc.get_circ_types().then(function(list){
1966             $scope.circ_type_list = list;
1967         });
1968         createSimpleUpdateWatcher('circ_as_type');
1969
1970         $scope.age_protect_list = [];
1971         itemSvc.get_age_protects().then(function(list){
1972             $scope.age_protect_list = list;
1973         });
1974         createSimpleUpdateWatcher('age_protect');
1975
1976         $scope.floating_list = [];
1977         itemSvc.get_floating_groups().then(function(list){
1978             $scope.floating_list = list;
1979         });
1980         createSimpleUpdateWatcher('floating');
1981
1982         createSimpleUpdateWatcher('circ_lib');
1983         createSimpleUpdateWatcher('circulate');
1984         createSimpleUpdateWatcher('holdable');
1985         createSimpleUpdateWatcher('fine_level');
1986         createSimpleUpdateWatcher('loan_duration');
1987         createSimpleUpdateWatcher('price');
1988         createSimpleUpdateWatcher('cost');
1989         createSimpleUpdateWatcher('deposit');
1990         createSimpleUpdateWatcher('deposit_amount');
1991         createSimpleUpdateWatcher('mint_condition');
1992         createSimpleUpdateWatcher('opac_visible');
1993         createSimpleUpdateWatcher('ref');
1994
1995         $scope.saveCompletedCopies = function (and_exit) {
1996             var cnHash = {};
1997             var perCnCopies = {};
1998             angular.forEach( $scope.completed_copies, function (cp) {
1999                 var cn = cp.call_number();
2000                 var cn_cps = cp.call_number().copies();
2001                 cp.call_number().copies([]);
2002                 var cn_id = cp.call_number().id();
2003                 cp.call_number(cn_id); // prevent loops in JSON-ification
2004                 if (!cnHash[cn_id]) {
2005                     cnHash[cn_id] = egCore.idl.Clone(cn);
2006                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
2007                 } else {
2008                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
2009                 }
2010                 cp.call_number(cn); // put the data back
2011                 cp.call_number().copies(cn_cps);
2012                 if (typeof cnHash[cn_id].prefix() == 'object')
2013                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
2014                 if (typeof cnHash[cn_id].suffix() == 'object')
2015                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
2016             });
2017
2018             if ($scope.only_vols) { // strip off copies when we're in vol-only mode
2019                 angular.forEach(cnHash, function (v, k) {
2020                     cnHash[k].copies([]);
2021                 });
2022             } else {
2023                 angular.forEach(perCnCopies, function (v, k) {
2024                     cnHash[k].copies(v);
2025                 });
2026             }
2027
2028             cnList = [];
2029             angular.forEach(cnHash, function (v, k) {
2030                 cnList.push(v);
2031             });
2032
2033             egNet.request(
2034                 'open-ils.cat',
2035                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
2036                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1, return_copy_ids : 1 }
2037             ).then(function(copy_ids) {
2038                 if (and_exit) {
2039                     $scope.dirty = false;
2040                     if ($scope.defaults.print_item_labels) {
2041                         egCore.net.request(
2042                             'open-ils.actor',
2043                             'open-ils.actor.anon_cache.set_value',
2044                             null, 'print-labels-these-copies', {
2045                                 copies : copy_ids
2046                             }
2047                         ).then(function(key) {
2048                             if (key) {
2049                                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
2050                                 $timeout(function() { $window.open(url, '_blank') }).then(
2051                                     function() { $timeout(function(){$window.close()}); }
2052                                 );
2053                             } else {
2054                                 alert('Could not create anonymous cache key!');
2055                             }
2056                         });
2057                     } else {
2058                         $timeout(function(){
2059                             if (typeof BroadcastChannel != 'undefined') {
2060                                 var bChannel = new BroadcastChannel("eg.holdings.update");
2061                                 var bre_ids = cnList && cnList.length > 0 ? cnList.map(function(cn){ return Number(cn.record()) }) : [];
2062                                 var cn_ids = cnList && cnList.length > 0 ? cnList.map(function(cn){ return cn.id() }) : [];
2063                                 bChannel.postMessage({
2064                                     copies : copy_ids,
2065                                     volumes: cn_ids,
2066                                     records: bre_ids
2067                                 });
2068                             }
2069
2070                             $window.close();
2071                         });
2072                     }
2073                 }
2074             });
2075         }
2076
2077         $scope.saveAndContinue = function () {
2078             $scope.saveCompletedCopies(false);
2079         }
2080
2081         $scope.workingSaveAndExit = function () {
2082             $scope.workingToComplete();
2083             $scope.saveAndExit();
2084         }
2085
2086         $scope.saveAndExit = function () {
2087             $scope.saveCompletedCopies(true);
2088         }
2089
2090     }
2091
2092     $scope.copy_notes_dialog = function(copy_list) {
2093         var default_pub = Boolean($scope.defaults.copy_notes_pub);
2094         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2095
2096         return $uibModal.open({
2097             templateUrl: './cat/volcopy/t_copy_notes',
2098             backdrop: 'static',
2099             animation: true,
2100             controller:
2101                    ['$scope','$uibModalInstance',
2102             function($scope , $uibModalInstance) {
2103                 $scope.focusNote = true;
2104                 $scope.note = {
2105                     creator : egCore.auth.user().id(),
2106                     title   : '',
2107                     value   : '',
2108                     pub     : default_pub,
2109                 };
2110
2111                 $scope.require_initials = false;
2112                 egCore.org.settings([
2113                     'ui.staff.require_initials.copy_notes'
2114                 ]).then(function(set) {
2115                     $scope.require_initials_ous = Boolean(set['ui.staff.require_initials.copy_notes']);
2116                 });
2117
2118                 $scope.are_initials_required = function() {
2119                   $scope.require_initials = $scope.require_initials_ous && ($scope.note.value.length > 0 || $scope.note.title.length > 0);
2120                 };
2121
2122                 $scope.$watch('note.value.length', $scope.are_initials_required);
2123                 $scope.$watch('note.title.length', $scope.are_initials_required);
2124
2125                 $scope.note_list = [];
2126                 if (copy_list.length == 1) {
2127                     $scope.note_list = copy_list[0].notes();
2128                 }
2129
2130                 $scope.ok = function(note) {
2131
2132                     if (note.value.length > 0 || note.title.length > 0) {
2133                         if ($scope.initials) {
2134                             note.value = egCore.strings.$replace(
2135                                 egCore.strings.COPY_NOTE_INITIALS, {
2136                                 value : note.value,
2137                                 initials : $scope.initials,
2138                                 ws_ou : egCore.org.get(
2139                                     egCore.auth.user().ws_ou()).shortname()
2140                             });
2141                         }
2142
2143                         angular.forEach(copy_list, function (cp) {
2144                             if (!angular.isArray(cp.notes())) cp.notes([]);
2145                             var n = new egCore.idl.acpn();
2146                             n.isnew(1);
2147                             n.creator(note.creator);
2148                             n.pub(note.pub ? 't' : 'f');
2149                             n.title(note.title);
2150                             n.value(note.value);
2151                             n.owning_copy(cp.id());
2152                             cp.notes().push( n );
2153                         });
2154                     }
2155
2156                     $uibModalInstance.close();
2157                 }
2158
2159                 $scope.cancel = function($event) {
2160                     $uibModalInstance.dismiss();
2161                     $event.preventDefault();
2162                 }
2163             }]
2164         });
2165     }
2166
2167     $scope.copy_tags_dialog = function(copy_list) {
2168         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2169
2170         return $uibModal.open({
2171             templateUrl: './cat/volcopy/t_copy_tags',
2172             backdrop: 'static',
2173             animation: true,
2174             controller:
2175                    ['$scope','$uibModalInstance',
2176             function($scope , $uibModalInstance) {
2177
2178                 $scope.tag_map = [];
2179                 var tag_hash = {};
2180                 var shared_tags = {};
2181                 angular.forEach(copy_list, function (cp) {
2182                     angular.forEach(cp.tags(), function(tag) {
2183                         if (!(tag.tag().id() in shared_tags)) {
2184                             shared_tags[tag.tag().id()] = 1;
2185                         } else {
2186                             shared_tags[tag.tag().id()]++;
2187                         }
2188                         if (!(tag.tag().id() in tag_hash)) {
2189                             tag_hash[tag.tag().id()] = tag;
2190                         }
2191                     });
2192                 });
2193                 angular.forEach(tag_hash, function(value, key) {
2194                     if (shared_tags[key] == copy_list.length) {
2195                         $scope.tag_map.push(value);
2196                     }
2197                 });
2198
2199                 $scope.tag_types = [];
2200                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
2201                     $scope.tag_types = list;
2202                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
2203                 });
2204
2205                 $scope.getTags = function(val) {
2206                     return egCore.pcrud.search('acpt',
2207                         { 
2208                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
2209                             label : { 'startwith' : {
2210                                         transform: 'evergreen.lowercase',
2211                                         value : [ 'evergreen.lowercase', val ]
2212                                     }},
2213                             tag_type : $scope.tag_type
2214                         },
2215                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
2216                     ).then(function(list) {
2217                         return list.map(function(item) {
2218                             return { value: item.label(), display: item.label() + " (" + egCore.org.get(item.owner()).shortname() + ")" };
2219                         });
2220                     });
2221                 }
2222
2223                 $scope.addTag = function() {
2224                     var tagLabel = $scope.selectedLabel;
2225                     // clear the typeahead
2226                     $scope.selectedLabel = "";
2227
2228                     // first, check tags already associated with the copy
2229                     var foundMatch = false;
2230                     angular.forEach($scope.tag_map, function(tag) {
2231                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
2232                             foundMatch = true;
2233                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
2234                         }
2235                     });
2236                     if (!foundMatch) {
2237                         egCore.pcrud.search('acpt',
2238                             { 
2239                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
2240                                 label : tagLabel,
2241                                 tag_type : $scope.tag_type
2242                             },
2243                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
2244                         ).then(function(list) {
2245                             if (list.length > 0) {
2246                                 var newMap = new egCore.idl.acptcm();
2247                                 newMap.isnew(1);
2248                                 newMap.copy(copy_list[0].id());
2249                                 newMap.tag(egCore.idl.Clone(list[0]));
2250                                 $scope.tag_map.push(newMap);
2251                             } else {
2252                                 var newTag = new egCore.idl.acpt();
2253                                 newTag.isnew(1);
2254                                 newTag.owner(egCore.auth.user().ws_ou());
2255                                 newTag.label(tagLabel);
2256                                 newTag.pub('t');
2257                                 newTag.tag_type($scope.tag_type);
2258
2259                                 var newMap = new egCore.idl.acptcm();
2260                                 newMap.isnew(1);
2261                                 newMap.copy(copy_list[0].id());
2262                                 newMap.tag(newTag);
2263                                 $scope.tag_map.push(newMap);
2264                             }
2265                         });
2266                     }
2267                 }
2268
2269                 $scope.ok = function(note) {
2270                     // in the multi-item case, this works OK for
2271                     // adding new maps to existing tags, but doesn't handle
2272                     // all possibilities
2273                     angular.forEach(copy_list, function (cp) {
2274                         cp.tags($scope.tag_map);
2275                     });
2276                     $uibModalInstance.close();
2277                 }
2278
2279                 $scope.cancel = function($event) {
2280                     $uibModalInstance.dismiss();
2281                     $event.preventDefault();
2282                 }
2283             }]
2284         });
2285     }
2286
2287     $scope.copy_alerts_dialog = function(copy_list) {
2288         if (!angular.isArray(copy_list)) copy_list = [copy_list];
2289
2290         return $uibModal.open({
2291             templateUrl: './cat/volcopy/t_copy_alerts',
2292             animation: true,
2293             controller:
2294                    ['$scope','$uibModalInstance',
2295             function($scope , $uibModalInstance) {
2296
2297                 itemSvc.get_copy_alert_types().then(function(ccat) {
2298                     $scope.alert_types = ccat;
2299                 });
2300
2301                 $scope.focusNote = true;
2302                 $scope.copy_alert = {
2303                     create_staff : egCore.auth.user().id(),
2304                     note         : '',
2305                     temp         : false
2306                 };
2307
2308                 egCore.hatch.getItem('cat.copy.alerts.last_type').then(function(t) {
2309                     if (t) $scope.copy_alert.alert_type = t;
2310                 });
2311
2312                 if (copy_list.length == 1) {
2313                     $scope.copy_alert_list = copy_list[0].copy_alerts();
2314                 }
2315
2316                 $scope.ok = function(copy_alert) {
2317
2318                     if (typeof(copy_alert.note) != 'undefined' &&
2319                         copy_alert.note != '') {
2320                         angular.forEach(copy_list, function (cp) {
2321                             if (!angular.isArray(cp.copy_alerts())) cp.copy_alerts([]);
2322                             var a = new egCore.idl.aca();
2323                             a.isnew(1);
2324                             a.create_staff(copy_alert.create_staff);
2325                             a.note(copy_alert.note);
2326                             a.temp(copy_alert.temp ? 't' : 'f');
2327                             a.copy(cp.id());
2328                             a.ack_time(null);
2329                             a.alert_type(
2330                                 $scope.alert_types.filter(function(at) {
2331                                     return at.id() == copy_alert.alert_type;
2332                                 })[0]
2333                             );
2334                             cp.copy_alerts().push( a );
2335                         });
2336
2337                         if (copy_alert.alert_type) {
2338                             egCore.hatch.setItem(
2339                                 'cat.copy.alerts.last_type',
2340                                 copy_alert.alert_type
2341                             );
2342                         }
2343
2344                     }
2345
2346                     $uibModalInstance.close();
2347                 }
2348
2349                 $scope.cancel = function($event) {
2350                     $uibModalInstance.dismiss();
2351                     $event.preventDefault();
2352                 }
2353             }]
2354         });
2355     }
2356
2357 }])
2358
2359 .directive("egVolTemplate", function () {
2360     return {
2361         restrict: 'E',
2362         replace: true,
2363         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
2364         scope: {
2365             editTemplates: '=',
2366         },
2367         controller : ['$scope','$window','itemSvc','egCore','ngToast','$uibModal',
2368             function ( $scope , $window , itemSvc , egCore , ngToast , $uibModal) {
2369
2370                 $scope.i18n = egCore.i18n;
2371
2372                 $scope.defaults = { // If defaults are not set at all, allow everything
2373                     barcode_checkdigit : false,
2374                     auto_gen_barcode : false,
2375                     statcats : true,
2376                     copy_notes : true,
2377                     copy_tags : true,
2378                     copy_alerts : true,
2379                     attributes : {
2380                         status : true,
2381                         loan_duration : true,
2382                         fine_level : true,
2383                         cost : true,
2384                         alerts : true,
2385                         deposit : true,
2386                         deposit_amount : true,
2387                         opac_visible : true,
2388                         price : true,
2389                         circulate : true,
2390                         mint_condition : true,
2391                         circ_lib : true,
2392                         ref : true,
2393                         circ_modifier : true,
2394                         circ_as_type : true,
2395                         location : true,
2396                         holdable : true,
2397                         age_protect : true,
2398                         floating : true
2399                     }
2400                 };
2401
2402                 $scope.fetchDefaults = function () {
2403                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
2404                         if (t) {
2405                             $scope.defaults = t;
2406                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
2407                             if (
2408                                     typeof $scope.defaults.statcat_filter == 'object' &&
2409                                     Object.keys($scope.defaults.statcat_filter).length > 0
2410                                 ) {
2411                                 // want fieldmapper object here...
2412                                 $scope.defaults.statcat_filter =
2413                                     egCore.idl.Clone($scope.defaults.statcat_filter);
2414                                 // ... and ID here
2415                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
2416                             }
2417                         }
2418                     });
2419                 }
2420                 $scope.fetchDefaults();
2421
2422                 $scope.dirty = false;
2423                 $scope.$watch('dirty',
2424                     function(newVal, oldVal) {
2425                         if (newVal && newVal != oldVal) {
2426                             $($window).on('beforeunload.template', function(){
2427                                 return 'There is unsaved template data!'
2428                             });
2429                         } else {
2430                             $($window).off('beforeunload.template');
2431                         }
2432                     }
2433                 );
2434
2435                 $scope.template_controls = true;
2436
2437                 $scope.fetchTemplates = function () {
2438                     itemSvc.get_acp_templates().then(function(t) {
2439                         if (t) {
2440                             $scope.templates = t;
2441                             $scope.template_name_list = Object.keys(t).sort();
2442                         }
2443                     });
2444                 }
2445                 $scope.fetchTemplates();
2446             
2447                 $scope.applyTemplate = function (n) {
2448                     angular.forEach($scope.templates[n], function (v,k) {
2449                         if (k == 'circ_lib') {
2450                             $scope.working[k] = egCore.org.get(v);
2451                         } else if (angular.isArray(v) || !angular.isObject(v)) {
2452                             $scope.working[k] = angular.copy(v);
2453                         } else {
2454                             angular.forEach(v, function (sv,sk) {
2455                                 if (!(k in $scope.working))
2456                                     $scope.working[k] = {};
2457                                 $scope.working[k][sk] = angular.copy(sv);
2458                             });
2459                         }
2460                     });
2461                     $scope.template_name = '';
2462                 }
2463
2464                 $scope.deleteTemplate = function (n) {
2465                     if (n) {
2466                         delete $scope.templates[n]
2467                         $scope.template_name_list = Object.keys($scope.templates).sort();
2468                         $scope.template_name = '';
2469                         itemSvc.save_acp_templates($scope.templates);
2470                         $scope.$parent.fetchTemplates();
2471                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
2472                     }
2473                 }
2474
2475                 $scope.saveTemplate = function (n) {
2476                     if (n) {
2477                         var tmpl = {};
2478             
2479                         angular.forEach($scope.working, function (v,k) {
2480                             if (angular.isObject(v)) { // we'll use the pkey
2481                                 if (v.id) v = v.id();
2482                                 else if (v.code) v = v.code();
2483                                 else v = angular.copy(v); // Should only be statcats and callnumbers currently
2484                             }
2485             
2486                             tmpl[k] = v;
2487                         });
2488             
2489                         $scope.templates[n] = tmpl;
2490                         $scope.template_name_list = Object.keys($scope.templates).sort();
2491             
2492                         itemSvc.save_acp_templates($scope.templates);
2493                         $scope.$parent.fetchTemplates();
2494
2495                         $scope.dirty = false;
2496                     } else {
2497                         // save all templates, as we might do after an import
2498                         itemSvc.save_acp_templates($scope.templates);
2499                         $scope.$parent.fetchTemplates();
2500                     }
2501                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
2502                 }
2503
2504                 $scope.templates = {};
2505                 $scope.imported_templates = { data : '' };
2506                 $scope.template_name = '';
2507                 $scope.template_name_list = [];
2508
2509                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
2510                     if (newVal && newVal != oldVal) {
2511                         try {
2512                             var newTemplates = JSON.parse(newVal);
2513                             if (!Object.keys(newTemplates).length) return;
2514                             angular.forEach(Object.keys(newTemplates), function (k) {
2515                                 $scope.templates[k] = newTemplates[k];
2516                             });
2517                             itemSvc.save_acp_templates($scope.templates);
2518                             $scope.fetchTemplates();
2519                         } catch (E) {
2520                             console.log('tried to import an invalid copy template file');
2521                         }
2522                     }
2523                 });
2524
2525                 $scope.tracker = function (x,f) { if (x) return x[f]() };
2526                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
2527                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
2528             
2529                 $scope.orgById = function (id) { return egCore.org.get(id) }
2530                 $scope.statusById = function (id) {
2531                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
2532                 }
2533                 $scope.locationById = function (id) {
2534                     return $scope.location_cache[''+id];
2535                 }
2536             
2537                 createSimpleUpdateWatcher = function (field) {
2538                     $scope.$watch('working.' + field, function () {
2539                         var newval = $scope.working[field];
2540             
2541                         if (typeof newval != 'undefined') {
2542                             $scope.dirty = true;
2543                             if (angular.isObject(newval)) { // we'll use the pkey
2544                                 if (newval.id) $scope.working[field] = newval.id();
2545                                 else if (newval.code) $scope.working[field] = newval.code();
2546                             }
2547             
2548                             if (""+newval == "" || newval == null) {
2549                                 $scope.working[field] = undefined;
2550                             }
2551             
2552                         }
2553                     });
2554                 }
2555             
2556                 $scope.working = {
2557                     copy_notes: [],
2558                     copy_alerts: [],
2559                     statcats: {},
2560                     statcat_filter: undefined
2561                 };
2562             
2563                 $scope.statcat_visible = function (sc_owner) {
2564                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
2565                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
2566                         if ($scope.working.statcat_filter == ancestor_org.id())
2567                             visible = true;
2568                     });
2569                     return visible;
2570                 }
2571
2572                 createStatcatUpdateWatcher = function (id) {
2573                     return $scope.$watch('working.statcats[' + id + ']', function () {
2574                         if ($scope.working.statcats) {
2575                             var newval = $scope.working.statcats[id];
2576                 
2577                             if (typeof newval != 'undefined') {
2578                                 $scope.dirty = true;
2579                                 if (angular.isObject(newval)) { // we'll use the pkey
2580                                     newval = newval.id();
2581                                 }
2582                 
2583                                 if (""+newval == "" || newval == null) {
2584                                     $scope.working.statcats[id] = undefined;
2585                                     newval = null;
2586                                 }
2587                 
2588                             }
2589                         }
2590                     });
2591                 }
2592
2593                 $scope.clearWorking = function () {
2594                     angular.forEach($scope.working, function (v,k,o) {
2595                         if (!angular.isObject(v)) {
2596                             if (typeof v != 'undefined')
2597                                 $scope.working[k] = undefined;
2598                         } else if (k != 'circ_lib' && k != 'MultiMap') {
2599                             angular.forEach(v, function (sv,sk) {
2600                                 $scope.working[k][sk] = undefined;
2601                             });
2602                         }
2603                     });
2604                     $scope.working.circ_lib = undefined; // special
2605                     $scope.dirty = false;
2606                 }
2607
2608                 $scope.working = {};
2609                 $scope.location_orgs = [];
2610                 $scope.location_cache = {};
2611             
2612                 $scope.location_list = [];
2613                 itemSvc.get_locations_by_org(
2614                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2615                 ).then(function(list){
2616                     $scope.location_list = list;
2617                 });
2618                 createSimpleUpdateWatcher('location');
2619
2620                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2621
2622                 $scope.statcats = [];
2623                 itemSvc.get_statcats(
2624                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2625                 ).then(function(list){
2626                     $scope.statcats = list;
2627                     angular.forEach($scope.statcats, function (s) {
2628
2629                         if (!$scope.working)
2630                             $scope.working = { statcats: {}, statcat_filter: undefined};
2631                         if (!$scope.working.statcats)
2632                             $scope.working.statcats = {};
2633
2634                         $scope.working.statcats[s.id()] = undefined;
2635                         createStatcatUpdateWatcher(s.id());
2636                     });
2637                 });
2638
2639                 $scope.copy_notes_dialog = function() {
2640                     var default_pub = Boolean($scope.defaults.copy_notes_pub);
2641                     var working = $scope.working;
2642             
2643                     return $uibModal.open({
2644                         templateUrl: './cat/volcopy/t_copy_notes',
2645                         animation: true,
2646                         controller:
2647                             ['$scope','$uibModalInstance',
2648                         function($scope , $uibModalInstance) {
2649                             $scope.focusNote = true;
2650                             $scope.note = {
2651                                 title   : '',
2652                                 value   : '',
2653                                 pub     : default_pub,
2654                             };
2655
2656                             $scope.require_initials = false;
2657                             egCore.org.settings([
2658                                 'ui.staff.require_initials.copy_notes'
2659                             ]).then(function(set) {
2660                                 $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
2661                             });
2662
2663                             $scope.note_list = [];
2664                             angular.forEach(working.copy_notes, function(note) {
2665                                 var acpn = egCore.idl.fromHash('acpn', note);
2666                                 $scope.note_list.push(acpn);
2667                             });
2668
2669                             $scope.ok = function(note) {
2670
2671                                 if (!working.copy_notes) {
2672                                     working.copy_notes = [];
2673                                 }
2674
2675                                 // clear slate
2676                                 working.copy_notes.length = 0;
2677                                 angular.forEach($scope.note_list, function(existing_note) {
2678                                     if (!existing_note.isdeleted()) {
2679                                         working.copy_notes.push({
2680                                             pub : existing_note.pub() ? 't' : 'f',
2681                                             title : existing_note.title(),
2682                                             value : existing_note.value()
2683                                         });
2684                                     }
2685                                 });
2686
2687                                 // add new note, if any
2688                                 if (note.initials) note.value += ' [' + note.initials + ']';
2689                                 note.pub = note.pub ? 't' : 'f';
2690                                 if (note.title.length && note.value.length) {
2691                                     working.copy_notes.push(note);
2692                                 }
2693
2694                                 $uibModalInstance.close();
2695                             }
2696
2697                             $scope.cancel = function($event) {
2698                                 $uibModalInstance.dismiss();
2699                                 $event.preventDefault();
2700                             }
2701                         }]
2702                     });
2703                 }
2704             
2705                 $scope.copy_alerts_dialog = function() {
2706                     var working = $scope.working;
2707
2708                     return $uibModal.open({
2709                         templateUrl: './cat/volcopy/t_copy_alerts',
2710                         animation: true,
2711                         controller:
2712                             ['$scope','$uibModalInstance',
2713                         function($scope , $uibModalInstance) {
2714
2715                             itemSvc.get_copy_alert_types().then(function(ccat) {
2716                                 var ccat_map = {};
2717                                 $scope.alert_types = ccat;
2718                                 angular.forEach(ccat, function(t) {
2719                                     ccat_map[t.id()] = t;
2720                                 });
2721                                 $scope.copy_alert_list = [];
2722                                 angular.forEach(working.copy_alerts, function (alrt) {
2723                                     var aca = egCore.idl.fromHash('aca', alrt);
2724                                     aca.alert_type(ccat_map[alrt.alert_type]);
2725                                     aca.ack_time(null);
2726                                     $scope.copy_alert_list.push(aca);
2727                                 });
2728                             });
2729
2730                             $scope.focusNote = true;
2731                             $scope.copy_alert = {
2732                                 note         : '',
2733                                 temp         : false
2734                             };
2735
2736                             $scope.ok = function(copy_alert) {
2737             
2738                                 if (!working.copy_alerts) {
2739                                     working.copy_alerts = [];
2740                                 }
2741                                 // clear slate
2742                                 working.copy_alerts.length = 0;
2743
2744                                 angular.forEach($scope.copy_alert_list, function(alrt) {
2745                                     if (alrt.ack_time() == null) {
2746                                         working.copy_alerts.push({
2747                                             note : alrt.note(),
2748                                             temp : alrt.temp(),
2749                                             alert_type : alrt.alert_type().id()
2750                                         });
2751                                     }
2752                                 });
2753
2754                                 if (typeof(copy_alert.note) != 'undefined' &&
2755                                     copy_alert.note != '') {
2756                                     working.copy_alerts.push({
2757                                         note : copy_alert.note,
2758                                         temp : copy_alert.temp ? 't' : 'f',
2759                                         alert_type : copy_alert.alert_type
2760                                     });
2761                                 }
2762
2763                                 $uibModalInstance.close();
2764                             }
2765
2766                             $scope.cancel = function($event) {
2767                                 $uibModalInstance.dismiss();
2768                                 $event.preventDefault();
2769                             }
2770                         }]
2771                     });
2772                 }
2773
2774                 $scope.status_list = [];
2775                 itemSvc.get_magic_statuses().then(function(list){
2776                     $scope.magic_status_list = list;
2777                 });
2778                 itemSvc.get_statuses().then(function(list){
2779                     $scope.status_list = list;
2780                 });
2781                 createSimpleUpdateWatcher('status');
2782             
2783                 $scope.circ_modifier_list = [];
2784                 itemSvc.get_circ_mods().then(function(list){
2785                     $scope.circ_modifier_list = list;
2786                 });
2787                 createSimpleUpdateWatcher('circ_modifier');
2788             
2789                 $scope.circ_type_list = [];
2790                 itemSvc.get_circ_types().then(function(list){
2791                     $scope.circ_type_list = list;
2792                 });
2793                 createSimpleUpdateWatcher('circ_as_type');
2794             
2795                 $scope.age_protect_list = [];
2796                 itemSvc.get_age_protects().then(function(list){
2797                     $scope.age_protect_list = list;
2798                 });
2799                 createSimpleUpdateWatcher('age_protect');
2800
2801                 $scope.floating_list = [];
2802                 itemSvc.get_floating_groups().then(function(list){
2803                     $scope.floating_list = list;
2804                 });
2805                 createSimpleUpdateWatcher('floating');
2806
2807                 createSimpleUpdateWatcher('circulate');
2808                 createSimpleUpdateWatcher('holdable');
2809                 createSimpleUpdateWatcher('fine_level');
2810                 createSimpleUpdateWatcher('loan_duration');
2811                 createSimpleUpdateWatcher('cost');
2812                 createSimpleUpdateWatcher('deposit');
2813                 createSimpleUpdateWatcher('deposit_amount');
2814                 createSimpleUpdateWatcher('mint_condition');
2815                 createSimpleUpdateWatcher('opac_visible');
2816                 createSimpleUpdateWatcher('ref');
2817
2818                 $scope.suffix_list = [];
2819                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2820                     $scope.suffix_list = list;
2821                 });
2822
2823                 $scope.prefix_list = [];
2824                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2825                     $scope.prefix_list = list;
2826                 });
2827
2828                 $scope.classification_list = [];
2829                 itemSvc.get_classifications().then(function(list){
2830                     $scope.classification_list = list;
2831                 });
2832
2833                 createSimpleUpdateWatcher('working.callnumber.classification');
2834                 createSimpleUpdateWatcher('working.callnumber.prefix');
2835                 createSimpleUpdateWatcher('working.callnumber.suffix');
2836             }
2837         ]
2838     }
2839 })
2840
2841