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