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