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