39e4aafc77ae145db4b0a507a15a0d718e3bb646
[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     service.get_prefixes = function(org) {
120         return egCore.pcrud.search('acnp',
121             {owning_lib : egCore.org.fullPath(org, true)},
122             {order_by : { acnp : 'label_sortkey' }}, {atomic : true}
123         );
124
125     };
126
127     service.get_statcats = function(orgs) {
128         return egCore.pcrud.search('asc',
129             {owner : orgs},
130             { flesh : 1,
131               flesh_fields : {
132                 asc : ['owner','entries']
133               }
134             },
135             { atomic : true }
136         );
137     };
138
139     service.get_locations = function(orgs) {
140         return egCore.pcrud.search('acpl',
141             {owning_lib : orgs, deleted : 'f'},
142             {
143                 flesh : 1,
144                 flesh_fields : {
145                     acpl : ['owning_lib']
146                 },
147                 order_by : { acpl : 'name' }
148             },
149             {atomic : true}
150         );
151     };
152
153     service.get_suffixes = function(org) {
154         return egCore.pcrud.search('acns',
155             {owning_lib : egCore.org.fullPath(org, true)},
156             {order_by : { acns : 'label_sortkey' }}, {atomic : true}
157         );
158
159     };
160
161     service.get_magic_statuses = function() {
162         /* TODO: make these more configurable per lp1616170 */
163         return $q.when([
164              1  /* Checked out */
165             ,3  /* Lost */
166             ,6  /* In transit */
167             ,8  /* On holds shelf */
168             ,16 /* Long overdue */
169             ,18 /* Canceled Transit */
170         ]);
171     }
172
173     service.get_statuses = function() {
174         if (egCore.env.ccs)
175             return $q.when(egCore.env.ccs.list);
176
177         return egCore.pcrud.retrieveAll('ccs', {order_by : { ccs : 'name' }}, {atomic : true}).then(
178             function(list) {
179                 egCore.env.absorbList(list, 'ccs');
180                 return list;
181             }
182         );
183
184     };
185
186     service.get_circ_mods = function() {
187         if (egCore.env.ccm)
188             return $q.when(egCore.env.ccm.list);
189
190         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
191             function(list) {
192                 egCore.env.absorbList(list, 'ccm');
193                 return list;
194             }
195         );
196
197     };
198
199     service.get_circ_types = function() {
200         if (egCore.env.citm)
201             return $q.when(egCore.env.citm.list);
202
203         return egCore.pcrud.retrieveAll('citm', {}, {atomic : true}).then(
204             function(list) {
205                 egCore.env.absorbList(list, 'citm');
206                 return list;
207             }
208         );
209
210     };
211
212     service.get_age_protects = function() {
213         if (egCore.env.crahp)
214             return $q.when(egCore.env.crahp.list);
215
216         return egCore.pcrud.retrieveAll('crahp', {}, {atomic : true}).then(
217             function(list) {
218                 egCore.env.absorbList(list, 'crahp');
219                 return list;
220             }
221         );
222
223     };
224
225     service.get_floating_groups = function() {
226         if (egCore.env.cfg)
227             return $q.when(egCore.env.cfg.list);
228
229         return egCore.pcrud.retrieveAll('cfg', {}, {atomic : true}).then(
230             function(list) {
231                 egCore.env.absorbList(list, 'cfg');
232                 return list;
233             }
234         );
235
236     };
237
238     service.bmp_parts = {};
239     service.get_parts = function(rec) {
240         if (service.bmp_parts[rec])
241             return $q.when(service.bmp_parts[rec]);
242
243         return egCore.pcrud.search('bmp',
244             {record : rec, deleted : 'f'},
245             null, {atomic : true}
246         ).then(function(list) {
247             service.bmp_parts[rec] = list;
248             return list;
249         });
250
251     };
252
253     service.get_acp_templates = function() {
254         // Already downloaded for this user? Return local copy. Changing users or logging out causes another download
255         // so users always have their own templates, and any changes made on other machines appear as expected.
256         if (egCore.hatch.getSessionItem('cat.copy.templates.usr') == egCore.auth.user().id()) {
257             return egCore.hatch.getItem('cat.copy.templates').then(function(templ) {
258                 return templ;
259             });
260         } else {
261             // this can be disabled for debugging to force a re-download and translation of test templates
262             egCore.hatch.setSessionItem('cat.copy.templates.usr', egCore.auth.user().id());
263             return service.load_remote_acp_templates();
264         }
265
266     };
267
268     service.save_acp_templates = function(t) {
269         egCore.hatch.setItem('cat.copy.templates', t);
270         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
271             egCore.auth.token(), egCore.auth.user().id(), { "webstaff.cat.copy.templates": t });
272         // console.warn('Saved ' + JSON.stringify({"webstaff.cat.copy.templates": t}));
273     };
274
275     service.load_remote_acp_templates = function() {
276         // After the XUL Client is completely removed everything related
277         // to staff_client.copy_editor.templates and convert_xul_templates
278         // can be thrown away.
279         return egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.retrieve.authoritative',
280             egCore.auth.token(), egCore.auth.user().id(),
281             ['webstaff.cat.copy.templates','staff_client.copy_editor.templates']).then(function(settings) {
282                 if (settings['webstaff.cat.copy.templates']) {
283                     egCore.hatch.setItem('cat.copy.templates', settings['webstaff.cat.copy.templates']);
284                     return settings['webstaff.cat.copy.templates'];
285                 } else {
286                     if (settings['staff_client.copy_editor.templates']) {
287                         var new_templ = service.convert_xul_templates(settings['staff_client.copy_editor.templates']);
288                         egCore.hatch.setItem('cat.copy.templates', new_templ);
289                         // console.warn('Saving: ' + JSON.stringify({'webstaff.cat.copy.templates' : new_templ}));
290                         egCore.net.request('open-ils.actor', 'open-ils.actor.patron.settings.update',
291                             egCore.auth.token(), egCore.auth.user().id(), {'webstaff.cat.copy.templates' : new_templ});
292                         return new_templ;
293                     }
294                 }
295                 return {};
296         });
297     };
298
299     service.convert_xul_templates = function(xultempl) {
300         var conv_templ = {};
301         var templ_names = Object.keys(xultempl);
302         var name;
303         var xul_t;
304         var curr_templ;
305         var stat_cats;
306         var fields;
307         var curr_field;
308         var tmp_val;
309         var i, j;
310
311         if (templ_names) {
312             for (i=0; i < templ_names.length; i++) {
313                 name = templ_names[i];
314                 curr_templ = {};
315                 stat_cats = {};
316                 xul_t  = xultempl[name];
317                 fields = Object.keys(xul_t);
318
319                 if (fields.length > 0) {
320                     for (j=0; j < fields.length; j++) {
321                         curr_field = xul_t[fields[j]];
322                         var field_name = curr_field["field"];
323
324                         if ( field_name == null ) { continue; }
325                         if ( curr_field["value"] == "<HACK:KLUDGE:NULL>" ) { continue; }
326
327                         // floating changed from a boolean to an integer at one point;
328                         // take this opportunity to remove the boolean from any old templates
329                         if ( curr_field["type"] === "attribute" && field_name === "floating" ) {
330                             if ( curr_field["value"].match(/[tf]/) ) { continue; }
331                         }
332
333                         if ( curr_field["type"] === "stat_cat" ) {
334                             stat_cats[field_name] = parseInt(curr_field["value"]);
335                         } else {
336                             tmp_val = curr_field['value'];
337                             if ( tmp_val.toString().match(/^[-0-9.]+$/)) {
338                                 tmp_val = parseFloat(tmp_val);
339                             }
340
341                             if (field_name.match(/^batch_.*_menulist$/)) {
342                                 // special handling for volume fields
343                                 if (!("callnumber" in curr_templ)) curr_templ["callnumber"] = {};
344                                 if (field_name === "batch_class_menulist")  curr_templ["callnumber"]["classification"] = tmp_val;
345                                 if (field_name === "batch_prefix_menulist") curr_templ["callnumber"]["prefix"] = tmp_val;
346                                 if (field_name === "batch_suffix_menulist") curr_templ["callnumber"]["suffix"] = tmp_val;
347                             } else {
348                                 curr_templ[field_name] = tmp_val;
349                             }
350                         }
351                     }
352
353                     if ( (Object.keys(stat_cats)).length > 0 ) {
354                         curr_templ["statcats"] = stat_cats;
355                     }
356
357                     conv_templ[name] = curr_templ;
358                 }
359             }
360         }
361         return conv_templ;
362     };
363
364     service.flesh = {   
365         flesh : 3, 
366         flesh_fields : {
367             acp : ['call_number','parts','stat_cat_entries', 'notes', 'tags'],
368             acn : ['label_class','prefix','suffix'],
369             acptcm : ['tag']
370         }
371     }
372
373     service.addCopy = function (cp) {
374
375         if (!cp.parts()) cp.parts([]); // just in case...
376
377         var lib = cp.call_number().owning_lib();
378         var cn = cp.call_number().id();
379
380         if (!service.tree[lib]) service.tree[lib] = {};
381         if (!service.tree[lib][cn]) service.tree[lib][cn] = [];
382
383         service.tree[lib][cn].push(cp);
384         service.copies.push(cp);
385     }
386
387     service.checkDuplicateBarcode = function(bc, id) {
388         var final = false;
389         return egCore.pcrud.search('acp', { deleted : 'f', 'barcode' : bc, id : { '!=' : id } })
390             .then(
391                 function () { return final },
392                 function () { return final },
393                 function () { final = true; }
394             );
395     }
396
397     service.fetchIds = function(idList) {
398         service.tree = {}; // clear the tree on fetch
399         service.copies = []; // clear the copy list on fetch
400         return egCore.pcrud.search('acp', { 'id' : idList }, service.flesh).then(null,null,
401             function(copy) {
402                 service.addCopy(copy);
403             }
404         );
405     }
406
407     // create a new acp object with default values
408     // (both hard-coded and coming from OU settings)
409     service.generateNewCopy = function(callNumber, owningLib, isFastAdd, isNew) {
410         var cp = new egCore.idl.acp();
411         cp.id( --service.new_cp_id );
412         if (isNew) {
413             cp.isnew( true );
414         }
415         cp.circ_lib( owningLib );
416         cp.call_number( callNumber );
417         cp.deposit(0);
418         cp.price(0);
419         cp.deposit_amount(0);
420         cp.fine_level(2); // Normal
421         cp.loan_duration(2); // Normal
422         cp.location(1); // Stacks
423         cp.circulate('t');
424         cp.holdable('t');
425         cp.opac_visible('t');
426         cp.ref('f');
427         cp.mint_condition('t');
428         cp.empty_barcode = true;
429
430         var status_setting = isFastAdd ?
431             'cat.default_copy_status_fast' :
432             'cat.default_copy_status_normal';
433         egCore.org.settings(
434             [status_setting],
435             owningLib
436         ).then(function(set) {
437             var default_ccs = parseInt(set[status_setting]);
438             if (isNaN(default_ccs))
439                 default_ccs = (isFastAdd ? 0 : 5); // 0 is Available, 5 is In Process
440             cp.status(default_ccs);
441         });
442
443         return cp;
444     }
445
446     return service;
447 }])
448
449 .directive("egVolCopyEdit", function () {
450     return {
451         restrict: 'E',
452         replace: true,
453         template:
454             '<div class="row">'+
455                 '<div class="col-xs-5" ng-class="{'+"'has-error'"+':barcode_has_error}">'+
456                     '<input id="{{callNumber.id()}}_{{copy.id()}}"'+
457                     ' eg-enter="nextBarcode(copy.id())" class="form-control"'+
458                     ' type="text" ng-model="barcode" ng-change="updateBarcode()"/>'+
459                     '<div class="label label-danger" ng-if="duplicate_barcode">{{duplicate_barcode_string}}</div>'+
460                     '<div class="label label-danger" ng-if="empty_barcode">{{empty_barcode_string}}</div>'+
461                 '</div>'+
462                 '<div class="col-xs-3"><input class="form-control" type="number" min="1" ng-model="copy_number" ng-change="updateCopyNo()"/></div>'+
463                 '<div class="col-xs-4"><eg-basic-combo-box eg-disabled="record == 0" list="parts" selected="part"></eg-basic-combo-box></div>'+
464             '</div>',
465
466         scope: { focusNext: "=", copy: "=", callNumber: "=", index: "@", record: "@" },
467         controller : ['$scope','itemSvc','egCore',
468             function ( $scope , itemSvc , egCore ) {
469                 $scope.new_part_id = 0;
470                 $scope.barcode_has_error = false;
471                 $scope.duplicate_barcode = false;
472                 $scope.empty_barcode = false;
473                 $scope.duplicate_barcode_string = window.duplicate_barcode_string;
474                 $scope.empty_barcode_string = window.empty_barcode_string;
475
476                 if (!$scope.copy.barcode()) $scope.copy.empty_barcode = true;
477
478                 $scope.nextBarcode = function (i) {
479                     $scope.focusNext(i, $scope.barcode);
480                 }
481
482                 $scope.updateBarcode = function () {
483                     if ($scope.barcode != '') {
484                         $scope.copy.empty_barcode = $scope.empty_barcode = false;
485                         $scope.barcode_has_error = !Boolean(itemSvc.checkBarcode($scope.barcode));
486                         itemSvc.checkDuplicateBarcode($scope.barcode, $scope.copy.id())
487                             .then(function (state) { $scope.copy.duplicate_barcode = $scope.duplicate_barcode = state });
488                     } else {
489                         $scope.copy.empty_barcode = $scope.empty_barcode = true;
490                     }
491                         
492                     $scope.copy.barcode($scope.barcode);
493                     $scope.copy.ischanged(1);
494                     if (itemSvc.currently_generating)
495                         $scope.focusNext($scope.copy.id(), $scope.barcode);
496                 };
497
498                 $scope.updateCopyNo = function () { $scope.copy.copy_number($scope.copy_number); $scope.copy.ischanged(1); };
499                 $scope.updatePart = function () {
500                     if ($scope.part) {
501                         var p = $scope.part_list.filter(function (x) {
502                             return x.label() == $scope.part
503                         });
504                         if (p.length > 0) { // preexisting part
505                             $scope.copy.parts(p)
506                         } else { // create one...
507                             var part = new egCore.idl.bmp();
508                             part.id( --$scope.new_part_id );
509                             part.isnew( true );
510                             part.label( $scope.part );
511                             part.record( $scope.callNumber.record() );
512                             $scope.copy.parts([part]);
513                             $scope.copy.ischanged(1);
514                         }
515                     } else {
516                         $scope.copy.parts([]);
517                     }
518                     $scope.copy.ischanged(1);
519                 }
520                 $scope.$watch('part', $scope.updatePart);
521
522                 $scope.barcode = $scope.copy.barcode();
523                 $scope.copy_number = $scope.copy.copy_number();
524
525                 if ($scope.copy.parts()) {
526                     $scope.part = $scope.copy.parts()[0];
527                     if ($scope.part) $scope.part = $scope.part.label();
528                 };
529
530                 $scope.parts = [];
531                 $scope.part_list = [];
532
533                 itemSvc.get_parts($scope.callNumber.record()).then(function(list){
534                     $scope.part_list = list;
535                     angular.forEach(list, function(p){ $scope.parts.push(p.label()) });
536                     $scope.parts = angular.copy($scope.parts);
537                 });
538
539             }
540         ]
541
542     }
543 })
544
545 .directive("egVolRow", function () {
546     return {
547         restrict: 'E',
548         replace: true,
549         transclude: true,
550         template:
551             '<div class="row">'+
552                 '<div class="col-xs-2">'+
553                     '<select ng-disabled="record == 0" class="form-control" ng-model="classification" ng-change="updateClassification()" ng-options="cl.name() for cl in classification_list"/>'+
554                 '</div>'+
555                 '<div class="col-xs-1">'+
556                     '<select ng-disabled="record == 0" class="form-control" ng-model="prefix" ng-change="updatePrefix()" ng-options="p.label() for p in prefix_list"/>'+
557                 '</div>'+
558                 '<div class="col-xs-2">'+
559                     '<input ng-disabled="record == 0" class="form-control" type="text" ng-change="updateLabel()" ng-model="label"/>'+
560                     '<div class="label label-danger" ng-if="empty_label">{{empty_label_string}}</div>'+
561                 '</div>'+
562                 '<div class="col-xs-1">'+
563                     '<select ng-disabled="record == 0" class="form-control" ng-model="suffix" ng-change="updateSuffix()" ng-options="s.label() for s in suffix_list"/>'+
564                 '</div>'+
565                 '<div ng-hide="onlyVols" class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" ng-model="copy_count" min="{{orig_copy_count}}" ng-change="changeCPCount()"></div>'+
566                 '<div ng-hide="onlyVols" class="col-xs-5">'+
567                     '<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>'+
568                 '</div>'+
569             '</div>',
570
571         scope: {focusNext: "=", allcopies: "=", copies: "=", onlyVols: "=", record: "@" },
572         controller : ['$scope','itemSvc','egCore',
573             function ( $scope , itemSvc , egCore ) {
574                 $scope.callNumber =  $scope.copies[0].call_number();
575                 if (!$scope.callNumber.label()) $scope.callNumber.emtpy_label = true;
576
577                 $scope.empty_label = false;
578                 $scope.empty_label_string = window.empty_label_string;
579
580                 $scope.idTracker = function (x) { if (x && x.id) return x.id() };
581
582                 // XXX $() is not working! arg
583                 $scope.focusNextBarcode = function (i, prev_bc) {
584                     var n;
585                     var yep = false;
586                     angular.forEach($scope.copies, function (cp) {
587                         if (n) return;
588
589                         if (cp.id() == i) {
590                             yep = true;
591                             return;
592                         }
593
594                         if (yep) n = cp.id();
595                     });
596
597                     if (n) {
598                         var next = '#' + $scope.callNumber.id() + '_' + n;
599                         var el = $(next);
600                         if (el) {
601                             if (!itemSvc.currently_generating) el.focus();
602                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
603                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
604                                     el.focus();
605                                     el.val(bc);
606                                     el.trigger('change');
607                                 });
608                             } else {
609                                 itemSvc.currently_generating = false;
610                             }
611                         }
612                     } else {
613                         $scope.focusNext($scope.callNumber.id(),prev_bc)
614                     }
615                 }
616
617                 $scope.suffix_list = [];
618                 itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
619                     $scope.suffix_list = list;
620                     $scope.$watch('callNumber.suffix()', function (v) {
621                         if (angular.isObject(v)) v = v.id();
622                         $scope.suffix = $scope.suffix_list.filter( function (s) {
623                             return s.id() == v;
624                         })[0];
625                     });
626
627                 });
628                 $scope.updateSuffix = function () {
629                     angular.forEach($scope.copies, function(cp) {
630                         cp.call_number().suffix($scope.suffix);
631                         cp.call_number().ischanged(1);
632                     });
633                 }
634
635                 $scope.prefix_list = [];
636                 itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
637                     $scope.prefix_list = list;
638                     $scope.$watch('callNumber.prefix()', function (v) {
639                         if (angular.isObject(v)) v = v.id();
640                         $scope.prefix = $scope.prefix_list.filter(function (p) {
641                             return p.id() == v;
642                         })[0];
643                     });
644
645                 });
646                 $scope.updatePrefix = function () {
647                     angular.forEach($scope.copies, function(cp) {
648                         cp.call_number().prefix($scope.prefix);
649                         cp.call_number().ischanged(1);
650                     });
651                 }
652                 $scope.$watch('callNumber.owning_lib()', function(oldLib, newLib) {
653                     if (oldLib == newLib) return;
654                     var currentPrefix = $scope.callNumber.prefix();
655                     if (angular.isObject(currentPrefix)) currentPrefix = currentPrefix.id();
656                     itemSvc.get_prefixes($scope.callNumber.owning_lib()).then(function(list){
657                         $scope.prefix_list = list;
658                         var newPrefixId = $scope.prefix_list.filter(function (p) {
659                             return p.id() == currentPrefix;
660                         })[0] || -1;
661                         if (newPrefixId.id) newPrefixId = newPrefixId.id();
662                         $scope.prefix = $scope.prefix_list.filter(function (p) {
663                             return p.id() == newPrefixId;
664                         })[0];
665                         if ($scope.newPrefixId != currentPrefix) {
666                             $scope.callNumber.prefix($scope.prefix);
667                         }
668                     });
669                     var currentSuffix = $scope.callNumber.suffix();
670                     if (angular.isObject(currentSuffix)) currentSuffix = currentSuffix.id();
671                     itemSvc.get_suffixes($scope.callNumber.owning_lib()).then(function(list){
672                         $scope.suffix_list = list;
673                         var newSuffixId = $scope.suffix_list.filter(function (s) {
674                             return s.id() == currentSuffix;
675                         })[0] || -1;
676                         if (newSuffixId.id) newSuffixId = newSuffixId.id();
677                         $scope.suffix = $scope.suffix_list.filter(function (s) {
678                             return s.id() == newSuffixId;
679                         })[0];
680                         if ($scope.newSuffixId != currentSuffix) {
681                             $scope.callNumber.suffix($scope.suffix);
682                         }
683                     });
684                 });
685
686                 $scope.classification_list = [];
687                 itemSvc.get_classifications().then(function(list){
688                     $scope.classification_list = list;
689                     $scope.$watch('callNumber.label_class()', function (v) {
690                         if (angular.isObject(v)) v = v.id();
691                         $scope.classification = $scope.classification_list.filter(function (c) {
692                             return c.id() == v;
693                         })[0];
694                     });
695
696                 });
697                 $scope.updateClassification = function () {
698                     angular.forEach($scope.copies, function(cp) {
699                         cp.call_number().label_class($scope.classification);
700                         cp.call_number().ischanged(1);
701                     });
702                 }
703
704                 $scope.updateLabel = function () {
705                     if ($scope.label == '') {
706                         $scope.callNumber.empty_label = $scope.empty_label = true;
707                     } else {
708                         $scope.callNumber.empty_label = $scope.empty_label = false;
709                     }
710                     angular.forEach($scope.copies, function(cp) {
711                         cp.call_number().label($scope.label);
712                         cp.call_number().ischanged(1);
713                     });
714                 }
715
716                 $scope.$watch('callNumber.label()', function (v) {
717                     $scope.label = v;
718                 });
719
720                 $scope.prefix = $scope.callNumber.prefix();
721                 $scope.suffix = $scope.callNumber.suffix();
722                 $scope.classification = $scope.callNumber.label_class();
723                 $scope.label = $scope.callNumber.label();
724
725                 $scope.copy_count = $scope.copies.length;
726                 $scope.orig_copy_count = $scope.copy_count;
727
728                 $scope.changeCPCount = function () {
729                     while ($scope.copy_count > $scope.copies.length) {
730                         var cp = itemSvc.generateNewCopy(
731                             $scope.callNumber,
732                             $scope.callNumber.owning_lib(),
733                             $scope.fast_add,
734                             true
735                         );
736                         $scope.copies.push( cp );
737                         $scope.allcopies.push( cp );
738
739                     }
740
741                     if ($scope.copy_count >= $scope.orig_copy_count) {
742                         var how_many = $scope.copies.length - $scope.copy_count;
743                         if (how_many > 0) {
744                             var dead = $scope.copies.splice($scope.copy_count,how_many);
745                             $scope.callNumber.copies($scope.copies);
746
747                             // Trimming the global list is a bit more tricky
748                             angular.forEach( dead, function (d) {
749                                 angular.forEach( $scope.allcopies, function (l, i) { 
750                                     if (l === d) $scope.allcopies.splice(i,1);
751                                 });
752                             });
753                         }
754                     }
755                 }
756
757             }
758         ]
759
760     }
761 })
762
763 .directive("egVolEdit", function () {
764     return {
765         restrict: 'E',
766         replace: true,
767         template:
768             '<div class="row">'+
769                 '<div class="col-xs-1"><eg-org-selector alldisabled="{{record == 0}}" selected="owning_lib" disable-test="cant_have_vols"></eg-org-selector></div>'+
770                 '<div class="col-xs-1"><input ng-disabled="record == 0" class="form-control" type="number" min="{{orig_cn_count}}" ng-model="cn_count" ng-change="changeCNCount()"/></div>'+
771                 '<div class="col-xs-10">'+
772                     '<eg-vol-row only-vols="onlyVols" record="{{record}}"'+
773                         'ng-repeat="(cn,copies) in struct" '+
774                         'focus-next="focusNextFirst" copies="copies" allcopies="allcopies">'+
775                     '</eg-vol-row>'+
776                 '</div>'+
777             '</div>',
778
779         scope: { focusNext: "=", allcopies: "=", struct: "=", lib: "@", record: "@", onlyVols: "=" },
780         controller : ['$scope','itemSvc','egCore',
781             function ( $scope , itemSvc , egCore ) {
782                 $scope.first_cn = Object.keys($scope.struct)[0];
783                 $scope.full_cn = $scope.struct[$scope.first_cn][0].call_number();
784
785                 $scope.defaults = {};
786                 egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
787                     if (t) {
788                         $scope.defaults = t;
789                     }
790                 });
791
792                 $scope.focusNextFirst = function(prev_cn,prev_bc) {
793                     var n;
794                     var yep = false;
795                     angular.forEach(Object.keys($scope.struct).sort(), function (cn) {
796                         if (n) return;
797
798                         if (cn == prev_cn) {
799                             yep = true;
800                             return;
801                         }
802
803                         if (yep) n = cn;
804                     });
805
806                     if (n) {
807                         var next = '#' + n + '_' + $scope.struct[n][0].id();
808                         var el = $(next);
809                         if (el) {
810                             if (!itemSvc.currently_generating) el.focus();
811                             if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
812                                 itemSvc.nextBarcode(prev_bc).then(function(bc){
813                                     el.focus();
814                                     el.val(bc);
815                                     el.trigger('change');
816                                 });
817                             } else {
818                                 itemSvc.currently_generating = false;
819                             }
820                         }
821                     } else {
822                         $scope.focusNext($scope.lib, prev_bc);
823                     }
824                 }
825
826                 $scope.cn_count = Object.keys($scope.struct).length;
827                 $scope.orig_cn_count = $scope.cn_count;
828
829                 $scope.owning_lib = egCore.org.get($scope.lib);
830                 $scope.$watch('owning_lib', function (oldLib, newLib) {
831                     if (oldLib == newLib) return;
832                     angular.forEach( Object.keys($scope.struct), function (cn) {
833                         $scope.struct[cn][0].call_number().owning_lib( $scope.owning_lib.id() );
834                         $scope.struct[cn][0].call_number().ischanged(1);
835                     });
836                 });
837
838                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
839
840                 $scope.$watch('cn_count', function (n) {
841                     var o = Object.keys($scope.struct).length;
842                     if (n > o) { // adding
843                         for (var i = o; o < n; o++) {
844                             var cn = new egCore.idl.acn();
845                             cn.id( --itemSvc.new_cn_id );
846                             cn.isnew( true );
847                             cn.prefix( $scope.defaults.prefix || -1 );
848                             cn.suffix( $scope.defaults.suffix || -1 );
849                             cn.label_class( $scope.defaults.classification || 1 );
850                             cn.owning_lib( $scope.owning_lib.id() );
851                             cn.record( $scope.full_cn.record() );
852
853                             var cp = itemSvc.generateNewCopy(
854                                 cn,
855                                 $scope.owning_lib.id(),
856                                 $scope.fast_add,
857                                 true
858                             );
859
860                             $scope.struct[cn.id()] = [cp];
861                             $scope.allcopies.push(cp);
862                             if (!$scope.defaults.classification) {
863                                 egCore.org.settings(
864                                     ['cat.default_classification_scheme'],
865                                     cn.owning_lib()
866                                 ).then(function (val) {
867                                     cn.label_class(val['cat.default_classification_scheme']);
868                                 });
869                             }
870                         }
871                     } else if (n < o && n >= $scope.orig_cn_count) { // removing
872                         var how_many = o - n;
873                         var list = Object
874                                 .keys($scope.struct)
875                                 .sort(function(a, b){return parseInt(a)-parseInt(b)})
876                                 .filter(function(x){ return parseInt(x) <= 0 });
877                         for (var i = 0; i < how_many; i++) {
878                             // Trimming the global list is a bit more tricky
879                             angular.forEach($scope.struct[list[i]], function (d) {
880                                 angular.forEach( $scope.allcopies, function (l, j) { 
881                                     if (l === d) $scope.allcopies.splice(j,1);
882                                 });
883                             });
884                             delete $scope.struct[list[i]];
885                         }
886                     }
887                 });
888             }
889         ]
890
891     }
892 })
893
894 /**
895  * Edit controller!
896  */
897 .controller('EditCtrl', 
898        ['$scope','$q','$window','$routeParams','$location','$timeout','egCore','egNet','egGridDataProvider','itemSvc','$uibModal',
899 function($scope , $q , $window , $routeParams , $location , $timeout , egCore , egNet , egGridDataProvider , itemSvc , $uibModal) {
900
901     $scope.forms = {}; // Accessed by t_attr_edit.tt2
902     $scope.i18n = egCore.i18n;
903
904     $scope.defaults = { // If defaults are not set at all, allow everything
905         barcode_checkdigit : false,
906         auto_gen_barcode : false,
907         statcats : true,
908         copy_notes : true,
909         copy_tags : true,
910         attributes : {
911             status : true,
912             loan_duration : true,
913             fine_level : true,
914             cost : true,
915             alerts : true,
916             deposit : true,
917             deposit_amount : true,
918             opac_visible : true,
919             price : true,
920             circulate : true,
921             mint_condition : true,
922             circ_lib : true,
923             ref : true,
924             circ_modifier : true,
925             circ_as_type : true,
926             location : true,
927             holdable : true,
928             age_protect : true,
929             floating : true,
930             alert_message : true
931         }
932     };
933
934     $scope.new_lib_to_add = egCore.org.get(egCore.auth.user().ws_ou());
935     $scope.changeNewLib = function (org) {
936         $scope.new_lib_to_add = org;
937     }
938     $scope.addLibToStruct = function () {
939         var newLib = $scope.new_lib_to_add;
940         var cn = new egCore.idl.acn();
941         cn.id( --itemSvc.new_cn_id );
942         cn.isnew( true );
943         cn.prefix( $scope.defaults.prefix || -1 );
944         cn.suffix( $scope.defaults.suffix || -1 );
945         cn.label_class( $scope.defaults.classification || 1 );
946         cn.owning_lib( newLib.id() );
947         cn.record( $scope.record_id );
948
949         var cp = itemSvc.generateNewCopy(
950             cn,
951             newLib.id(),
952             $scope.fast_add,
953             true
954         );
955
956         $scope.data.addCopy(cp);
957
958         if (!$scope.defaults.classification) {
959             egCore.org.settings(
960                 ['cat.default_classification_scheme'],
961                 cn.owning_lib()
962             ).then(function (val) {
963                 cn.label_class(val['cat.default_classification_scheme']);
964             });
965         }
966     }
967
968     $scope.embedded = ($routeParams.mode && $routeParams.mode == 'embedded') ? true : false;
969     $scope.edit_templates = ($location.path().match(/edit_template/)) ? true : false;
970
971     $scope.saveDefaults = function () {
972         egCore.hatch.setItem('cat.copy.defaults', $scope.defaults);
973     }
974
975     $scope.fetchDefaults = function () {
976         egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
977             if (t) {
978                 $scope.defaults = t;
979                 if (!$scope.batch) $scope.batch = {};
980                 $scope.batch.classification = $scope.defaults.classification;
981                 $scope.batch.prefix = $scope.defaults.prefix;
982                 $scope.batch.suffix = $scope.defaults.suffix;
983                 $scope.working.statcat_filter = $scope.defaults.statcat_filter;
984                 if (
985                         typeof $scope.defaults.statcat_filter == 'object' &&
986                         Object.keys($scope.defaults.statcat_filter).length > 0
987                    ) {
988                     // want fieldmapper object here...
989                     $scope.defaults.statcat_filter =
990                          egCore.idl.Clone($scope.defaults.statcat_filter);
991                     // ... and ID here
992                     $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
993                 }
994                 if ($scope.defaults.always_volumes) $scope.show_vols = true;
995                 if ($scope.defaults.barcode_checkdigit) itemSvc.barcode_checkdigit = true;
996                 if ($scope.defaults.auto_gen_barcode) itemSvc.auto_gen_barcode = true;
997             }
998         });
999     }
1000     $scope.fetchDefaults();
1001
1002     $scope.$watch('defaults.statcat_filter', function() {
1003         $scope.saveDefaults();
1004     });
1005     $scope.$watch('defaults.auto_gen_barcode', function (n,o) {
1006         itemSvc.auto_gen_barcode = n
1007     });
1008
1009     $scope.$watch('defaults.barcode_checkdigit', function (n,o) {
1010         itemSvc.barcode_checkdigit = n
1011     });
1012
1013     $scope.dirty = false;
1014     $scope.$watch('dirty',
1015         function(newVal, oldVal) {
1016             if (newVal && newVal != oldVal) {
1017                 $($window).on('beforeunload.edit', function(){
1018                     return 'There is unsaved data!'
1019                 });
1020             } else {
1021                 $($window).off('beforeunload.edit');
1022             }
1023         }
1024     );
1025
1026     $scope.only_vols = false;
1027     $scope.show_vols = true;
1028     $scope.show_copies = true;
1029
1030     $scope.tracker = function (x,f) { if (x) return x[f]() };
1031     $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
1032     $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
1033
1034     $scope.orgById = function (id) { return egCore.org.get(id) }
1035     $scope.statusById = function (id) {
1036         return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
1037     }
1038     $scope.locationById = function (id) {
1039         return $scope.location_cache[''+id];
1040     }
1041
1042     $scope.workingToComplete = function () {
1043         angular.forEach( $scope.workingGridControls.selectedItems(), function (c) {
1044             angular.forEach( itemSvc.copies, function (w, i) {
1045                 if (c === w)
1046                     $scope.completed_copies = $scope.completed_copies.concat(itemSvc.copies.splice(i,1));
1047             });
1048         });
1049
1050         return true;
1051     }
1052
1053     $scope.completeToWorking = function () {
1054         angular.forEach( $scope.completedGridControls.selectedItems(), function (c) {
1055             angular.forEach( $scope.completed_copies, function (w, i) {
1056                 if (c === w)
1057                     itemSvc.copies = itemSvc.copies.concat($scope.completed_copies.splice(i,1));
1058             });
1059         });
1060
1061         return true;
1062     }
1063
1064     createSimpleUpdateWatcher = function (field,exclude_copies_with_one_of_these_values) {
1065         return $scope.$watch('working.' + field, function () {
1066             var newval = $scope.working[field];
1067
1068             if (typeof newval != 'undefined') {
1069                 if (angular.isObject(newval)) { // we'll use the pkey
1070                     if (newval.id) newval = newval.id();
1071                     else if (newval.code) newval = newval.code();
1072                 }
1073
1074                 if (""+newval == "" || newval == null) {
1075                     $scope.working[field] = undefined;
1076                     newval = null;
1077                 }
1078
1079                 if ($scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1080                     angular.forEach(
1081                         $scope.workingGridControls.selectedItems(),
1082                         function (cp) {
1083                             if (exclude_copies_with_one_of_these_values
1084                                 && exclude_copies_with_one_of_these_values.indexOf(cp[field](),0) > -1) {
1085                                 return;
1086                             }
1087                             if (cp[field]() !== newval) {
1088                                 cp[field](newval);
1089                                 cp.ischanged(1);
1090                                 $scope.dirty = true;
1091                             }
1092                         }
1093                     );
1094                 }
1095             }
1096         });
1097     }
1098
1099     $scope.working = {
1100         statcats: {},
1101         statcat_filter: undefined
1102     };
1103
1104     $scope.statcatUpdate = function (id) {
1105         var newval = $scope.working.statcats[id];
1106
1107         if (typeof newval != 'undefined') {
1108             if (angular.isObject(newval)) { // we'll use the pkey
1109                 newval = newval.id();
1110             }
1111     
1112             if (""+newval == "" || newval == null) {
1113                 $scope.working.statcats[id] = undefined;
1114                 newval = null;
1115             }
1116     
1117             if (!$scope.in_item_select && $scope.workingGridControls && $scope.workingGridControls.selectedItems) {
1118                 angular.forEach(
1119                     $scope.workingGridControls.selectedItems(),
1120                     function (cp) {
1121                         $scope.dirty = true;
1122
1123                         cp.stat_cat_entries(
1124                             angular.forEach( cp.stat_cat_entries(), function (e) {
1125                                 if (e.stat_cat() == id) { // mark deleted
1126                                     e.isdeleted(1);
1127                                 }
1128                             })
1129                         );
1130     
1131                         if (newval) {
1132                             var e = new egCore.idl.asce();
1133                             e.isnew( 1 );
1134                             e.stat_cat( id );
1135                             e.id(newval);
1136
1137                             cp.stat_cat_entries(
1138                                 cp.stat_cat_entries() ?
1139                                     cp.stat_cat_entries().concat([ e ]) :
1140                                     [ e ]
1141                             );
1142
1143                         }
1144
1145                         // trim out all deleted ones; the API used to
1146                         // do the update doesn't actually consult
1147                         // isdeleted for stat cat entries
1148                         cp.stat_cat_entries(
1149                             cp.stat_cat_entries().filter(function (e) {
1150                                 return !Boolean(e.isdeleted());
1151                             })
1152                         );
1153    
1154                         cp.ischanged(1);
1155                     }
1156                 );
1157             }
1158         }
1159     }
1160
1161     var dataKey = $routeParams.dataKey;
1162     console.debug('dataKey: ' + dataKey);
1163
1164     if ((dataKey && dataKey.length > 0) || $scope.edit_templates) {
1165
1166         $scope.templates = {};
1167         $scope.template_name = '';
1168         $scope.template_name_list = [];
1169
1170         $scope.fetchTemplates = function () {
1171             itemSvc.get_acp_templates().then(function(t) {
1172                 if (t) {
1173                     $scope.templates = t;
1174                     $scope.template_name_list = Object.keys(t).sort();
1175                 }
1176             });
1177             egCore.hatch.getItem('cat.copy.last_template').then(function(t) {
1178                 if (t) $scope.template_name = t;
1179             });
1180         }
1181         $scope.fetchTemplates();
1182
1183         $scope.applyTemplate = function (n) {
1184             angular.forEach($scope.templates[n], function (v,k) {
1185                 if (k == 'circ_lib') {
1186                     $scope.working[k] = egCore.org.get(v);
1187                 } else if (!angular.isObject(v)) {
1188                     $scope.working[k] = angular.copy(v);
1189                 } else {
1190                     angular.forEach(v, function (sv,sk) {
1191                         if (k == 'callnumber') {
1192                             angular.forEach(v, function (cnv,cnk) {
1193                                 $scope.batch[cnk] = cnv;
1194                             });
1195                             $scope.applyBatchCNValues();
1196                         } else {
1197                             $scope.working[k][sk] = angular.copy(sv);
1198                             if (k == 'statcats') $scope.statcatUpdate(sk);
1199                         }
1200                     });
1201                 }
1202             });
1203             egCore.hatch.setItem('cat.copy.last_template', n);
1204         }
1205
1206         $scope.copytab = 'working';
1207         $scope.tab = 'edit';
1208         $scope.summaryRecord = null;
1209         $scope.record_id = null;
1210         $scope.data = {};
1211         $scope.completed_copies = [];
1212         $scope.location_orgs = [];
1213         $scope.location_cache = {};
1214         $scope.statcats = [];
1215         if (!$scope.batch) $scope.batch = {};
1216
1217         $scope.applyBatchCNValues = function () {
1218             if ($scope.data.tree) {
1219                 angular.forEach($scope.data.tree, function(cn_hash) {
1220                     angular.forEach(cn_hash, function(copies) {
1221                         angular.forEach(copies, function(cp) {
1222                             if (typeof $scope.batch.classification != 'undefined' && $scope.batch.classification != '') {
1223                                 var label_class = $scope.classification_list.filter(function(p){ return p.id() == $scope.batch.classification })[0];
1224                                 cp.call_number().label_class(label_class);
1225                                 cp.call_number().ischanged(1);
1226                                 $scope.dirty = true;
1227                             }
1228                             if (typeof $scope.batch.prefix != 'undefined' && $scope.batch.prefix != '') {
1229                                 var prefix = $scope.prefix_list.filter(function(p){ return p.id() == $scope.batch.prefix })[0];
1230                                 cp.call_number().prefix(prefix);
1231                                 cp.call_number().ischanged(1);
1232                                 $scope.dirty = true;
1233                             }
1234                             if (typeof $scope.batch.label != 'undefined' && $scope.batch.label != '') {
1235                                 cp.call_number().label($scope.batch.label);
1236                                 cp.call_number().ischanged(1);
1237                                 $scope.dirty = true;
1238                             }
1239                             if (typeof $scope.batch.suffix != 'undefined' && $scope.batch.suffix != '') {
1240                                 var suffix = $scope.suffix_list.filter(function(p){ return p.id() == $scope.batch.suffix })[0];
1241                                 cp.call_number().suffix(suffix);
1242                                 cp.call_number().ischanged(1);
1243                                 $scope.dirty = true;
1244                             }
1245                         });
1246                     });
1247                 });
1248             }
1249         }
1250
1251         $scope.clearWorking = function () {
1252             angular.forEach($scope.working, function (v,k,o) {
1253                 if (!angular.isObject(v)) {
1254                     if (typeof v != 'undefined')
1255                         $scope.working[k] = undefined;
1256                 } else if (k != 'circ_lib') {
1257                     angular.forEach(v, function (sv,sk) {
1258                         if (typeof v != 'undefined')
1259                             $scope.working[k][sk] = undefined;
1260                     });
1261                 }
1262             });
1263             $scope.working.circ_lib = undefined; // special
1264         }
1265
1266         $scope.completedGridDataProvider = egGridDataProvider.instance({
1267             get : function(offset, count) {
1268                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1269                 return this.arrayNotifier($scope.completed_copies, offset, count);
1270             }
1271         });
1272
1273         $scope.completedGridControls = {};
1274
1275         $scope.workingGridDataProvider = egGridDataProvider.instance({
1276             get : function(offset, count) {
1277                 //return provider.arrayNotifier(itemSvc.copies, offset, count);
1278                 return this.arrayNotifier(itemSvc.copies, offset, count);
1279             }
1280         });
1281
1282         $scope.workingGridControls = {};
1283         $scope.add_vols_copies = false;
1284         $scope.is_fast_add = false;
1285
1286         egNet.request(
1287             'open-ils.actor',
1288             'open-ils.actor.anon_cache.get_value',
1289             dataKey, 'edit-these-copies'
1290         ).then(function (data) {
1291
1292             if (data) {
1293                 if (data.hide_vols && !$scope.defaults.always_volumes) $scope.show_vols = false;
1294                 if (data.hide_copies) {
1295                     $scope.show_copies = false;
1296                     $scope.only_vols = true;
1297                 }
1298
1299                 $scope.record_id = data.record_id;
1300
1301                 function fetchRaw () {
1302                     if (!$scope.only_vols) $scope.dirty = true;
1303                     $scope.add_vols_copies = true;
1304
1305                     /* data.raw data structure looks like this:
1306                      * [{
1307                      *      callnumber : $cn_id, // optional, to add a copy to a cn
1308                      *      owner      : $org, // optional, defaults to ws_ou
1309                      *      label      : $cn_label, // optional, to supply a label on a new cn
1310                      *      barcode    : $cp_barcode // optional, to supply a barcode on a new cp
1311                      *      fast_add   : boolean // optional, to specify whether this came
1312                      *                              in as a fast add
1313                      * },...]
1314                      * 
1315                      * All can be left out and a completely empty vol/copy combo will be vivicated.
1316                      */
1317
1318                     angular.forEach(
1319                         data.raw,
1320                         function (proto) {
1321                             if (proto.fast_add) $scope.is_fast_add = true;
1322                             if (proto.callnumber) {
1323                                 return egCore.pcrud.retrieve('acn', proto.callnumber)
1324                                 .then(function(cn) {
1325                                     var cp = new itemSvc.generateNewCopy(
1326                                         cn,
1327                                         proto.owner || egCore.auth.user().ws_ou(),
1328                                         $scope.is_fast_add,
1329                                         ((!$scope.only_vols) ? true : false)
1330                                     );
1331
1332                                     if (proto.barcode) {
1333                                         cp.barcode( proto.barcode );
1334                                         cp.empty_barcode = false;
1335                                     }
1336
1337                                     itemSvc.addCopy(cp)
1338                                 });
1339                             } else {
1340                                 var cn = new egCore.idl.acn();
1341                                 cn.id( --itemSvc.new_cn_id );
1342                                 cn.isnew( true );
1343                                 cn.prefix( $scope.defaults.prefix || -1 );
1344                                 cn.suffix( $scope.defaults.suffix || -1 );
1345                                 cn.owning_lib( proto.owner || egCore.auth.user().ws_ou() );
1346                                 cn.record( $scope.record_id );
1347                                 egCore.org.settings(
1348                                     ['cat.default_classification_scheme'],
1349                                     cn.owning_lib()
1350                                 ).then(function (val) {
1351                                     cn.label_class(
1352                                         $scope.defaults.classification ||
1353                                         val['cat.default_classification_scheme'] ||
1354                                         1
1355                                     );
1356                                     if (proto.label) {
1357                                         cn.label( proto.label );
1358                                     } else {
1359                                         egCore.net.request(
1360                                             'open-ils.cat',
1361                                             'open-ils.cat.biblio.record.marc_cn.retrieve',
1362                                             $scope.record_id,
1363                                             cn.label_class()
1364                                         ).then(function(cn_array) {
1365                                             if (cn_array.length > 0) {
1366                                                 for (var field in cn_array[0]) {
1367                                                     cn.label( cn_array[0][field] );
1368                                                     break;
1369                                                 }
1370                                             }
1371                                         });
1372                                     }
1373                                 });
1374
1375                                 var cp = new itemSvc.generateNewCopy(
1376                                     cn,
1377                                     proto.owner || egCore.auth.user().ws_ou(),
1378                                     $scope.is_fast_add,
1379                                     true
1380                                 );
1381
1382                                 if (proto.barcode) {
1383                                     cp.barcode( proto.barcode );
1384                                     cp.empty_barcode = false;
1385                                 }
1386
1387                                 itemSvc.addCopy(cp)
1388                             }
1389     
1390                         }
1391                     );
1392
1393                     return itemSvc.copies;
1394                 }
1395
1396                 if (data.copies && data.copies.length)
1397                     return itemSvc.fetchIds(data.copies).then(fetchRaw);
1398
1399                 return fetchRaw();
1400
1401             }
1402
1403         }).then( function() {
1404             $scope.data = itemSvc;
1405             $scope.workingGridDataProvider.refresh();
1406         });
1407
1408         $scope.can_save = false;
1409         function check_saveable () {
1410             var can_save = true;
1411             angular.forEach(
1412                 itemSvc.copies,
1413                 function (i) {
1414                     if (i.duplicate_barcode || i.empty_barcode || i.call_number().empty_label)
1415                         can_save = false;
1416                 }
1417             );
1418             if ($scope.forms.myForm && $scope.forms.myForm.$invalid) {
1419                 can_save = false;
1420             }
1421             $scope.can_save = can_save;
1422         }
1423
1424         $scope.disableSave = function () {
1425             check_saveable();
1426             return !$scope.can_save;
1427         }
1428
1429         $scope.focusNextFirst = function(prev_lib,prev_bc) {
1430             var n;
1431             var yep = false;
1432             angular.forEach(Object.keys($scope.data.tree).sort(), function (lib) {
1433                 if (n) return;
1434
1435                 if (lib == prev_lib) {
1436                     yep = true;
1437                     return;
1438                 }
1439
1440                 if (yep) n = lib;
1441             });
1442
1443             if (n) {
1444                 var first_cn = Object.keys($scope.data.tree[n])[0];
1445                 var next = '#' + first_cn + '_' + $scope.data.tree[n][first_cn][0].id();
1446                 var el = $(next);
1447                 if (el) {
1448                     if (!itemSvc.currently_generating) el.focus();
1449                     if (prev_bc && itemSvc.auto_gen_barcode && el.val() == "") {
1450                         itemSvc.nextBarcode(prev_bc).then(function(bc){
1451                             el.focus();
1452                             el.val(bc);
1453                             el.trigger('change');
1454                         });
1455                     } else {
1456                         itemSvc.currently_generating = false;
1457                     }
1458                 }
1459             }
1460         }
1461
1462         $scope.in_item_select = false;
1463         $scope.afterItemSelect = function() { $scope.in_item_select = false };
1464         $scope.handleItemSelect = function (item_list) {
1465             if (item_list && item_list.length > 0) {
1466                 $scope.in_item_select = true;
1467
1468                 angular.forEach(Object.keys($scope.defaults.attributes), function (attr) {
1469
1470                     var value_hash = {};
1471                     angular.forEach(item_list, function (item) {
1472                         if (item[attr]) {
1473                             var v = item[attr]()
1474                             if (angular.isObject(v)) {
1475                                 if (v.id) v = v.id();
1476                                 else if (v.code) v = v.code();
1477                             }
1478                             value_hash[v] = 1;
1479                         }
1480                     });
1481
1482                     if (Object.keys(value_hash).length == 1) {
1483                         if (attr == 'circ_lib') {
1484                             $scope.working[attr] = egCore.org.get(item_list[0][attr]());
1485                         } else {
1486                             $scope.working[attr] = item_list[0][attr]();
1487                         }
1488                     } else {
1489                         $scope.working[attr] = undefined;
1490                     }
1491                 });
1492
1493                 angular.forEach($scope.statcats, function (sc) {
1494
1495                     var counter = -1;
1496                     var value_hash = {};
1497                     var none = false;
1498                     angular.forEach(item_list, function (item) {
1499                         if (item.stat_cat_entries()) {
1500                             if (item.stat_cat_entries().length > 0) {
1501                                 var right_sc = item.stat_cat_entries().filter(function (e) {
1502                                     return e.stat_cat() == sc.id() && !Boolean(e.isdeleted());
1503                                 });
1504
1505                                 if (right_sc.length > 0) {
1506                                     value_hash[right_sc[0].id()] = right_sc[0].id();
1507                                 } else {
1508                                     none = true;
1509                                 }
1510                             }
1511                         } else {
1512                             none = true;
1513                         }
1514                     });
1515
1516                     if (!none && Object.keys(value_hash).length == 1) {
1517                         $scope.working.statcats[sc.id()] = value_hash[Object.keys(value_hash)[0]];
1518                     } else {
1519                         $scope.working.statcats[sc.id()] = undefined;
1520                     }
1521                 });
1522
1523             } else {
1524                 $scope.clearWorking();
1525             }
1526
1527         }
1528
1529         $scope.$watch('data.copies.length', function () {
1530             if ($scope.data.copies) {
1531                 var base_orgs = $scope.data.copies.map(function(cp){
1532                     return cp.circ_lib()
1533                 }).concat(
1534                     $scope.data.copies.map(function(cp){
1535                         return cp.call_number().owning_lib()
1536                     })
1537                 ).concat(
1538                     [egCore.auth.user().ws_ou()]
1539                 ).filter(function(e,i,a){
1540                     return a.lastIndexOf(e) === i;
1541                 });
1542
1543                 var all_orgs = [];
1544                 angular.forEach(base_orgs, function(o) {
1545                     all_orgs = all_orgs.concat( egCore.org.fullPath(o, true) );
1546                 });
1547
1548                 var final_orgs = all_orgs.filter(function(e,i,a){
1549                     return a.lastIndexOf(e) === i;
1550                 }).sort(function(a, b){return parseInt(a)-parseInt(b)});
1551
1552                 if ($scope.location_orgs.toString() != final_orgs.toString()) {
1553                     $scope.location_orgs = final_orgs;
1554                     if ($scope.location_orgs.length) {
1555                         itemSvc.get_locations($scope.location_orgs).then(function(list){
1556                             angular.forEach(list, function(l) {
1557                                 $scope.location_cache[ ''+l.id() ] = l;
1558                             });
1559                             $scope.location_list = list;
1560                         });
1561
1562                         $scope.statcat_filter_list = [];
1563                         angular.forEach($scope.location_orgs, function (o) {
1564                             $scope.statcat_filter_list.push(egCore.org.get(o));
1565                         });
1566
1567                         itemSvc.get_statcats($scope.location_orgs).then(function(list){
1568                             $scope.statcats = list;
1569                             angular.forEach($scope.statcats, function (s) {
1570
1571                                 if (!$scope.working)
1572                                     $scope.working = { statcats: {}, statcat_filter: undefined};
1573                                 if (!$scope.working.statcats)
1574                                     $scope.working.statcats = {};
1575
1576                                 if (!$scope.in_item_select) {
1577                                     $scope.working.statcats[s.id()] = undefined;
1578                                 }
1579                                 createStatcatUpdateWatcher(s.id());
1580                             });
1581                             $scope.in_item_select = false;
1582                             // do a refresh here to work around a race
1583                             // condition that can result in stat cats
1584                             // not being selected.
1585                             $scope.workingGridDataProvider.refresh();
1586                         });
1587                     }
1588                 }
1589             }
1590
1591             $scope.workingGridDataProvider.refresh();
1592         });
1593
1594         $scope.statcat_visible = function (sc_owner) {
1595             var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
1596             angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
1597                 if ($scope.working.statcat_filter == ancestor_org.id())
1598                     visible = true;
1599             });
1600             return visible;
1601         }
1602
1603         $scope.suffix_list = [];
1604         itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
1605             $scope.suffix_list = list;
1606         });
1607
1608         $scope.prefix_list = [];
1609         itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
1610             $scope.prefix_list = list;
1611         });
1612
1613         $scope.classification_list = [];
1614         itemSvc.get_classifications().then(function(list){
1615             $scope.classification_list = list;
1616         });
1617
1618         $scope.$watch('completed_copies.length', function () {
1619             $scope.completedGridDataProvider.refresh();
1620         });
1621
1622         $scope.location_list = [];
1623         itemSvc.get_locations().then(function(list){
1624             $scope.location_list = list;
1625         });
1626         createSimpleUpdateWatcher('location');
1627
1628         $scope.status_list = [];
1629         itemSvc.get_magic_statuses().then(function(list){
1630             $scope.magic_status_list = list;
1631             createSimpleUpdateWatcher('status',$scope.magic_status_list);
1632         });
1633         itemSvc.get_statuses().then(function(list){
1634             $scope.status_list = list;
1635         });
1636
1637         $scope.circ_modifier_list = [];
1638         itemSvc.get_circ_mods().then(function(list){
1639             $scope.circ_modifier_list = list;
1640         });
1641         createSimpleUpdateWatcher('circ_modifier');
1642
1643         $scope.circ_type_list = [];
1644         itemSvc.get_circ_types().then(function(list){
1645             $scope.circ_type_list = list;
1646         });
1647         createSimpleUpdateWatcher('circ_as_type');
1648
1649         $scope.age_protect_list = [];
1650         itemSvc.get_age_protects().then(function(list){
1651             $scope.age_protect_list = list;
1652         });
1653         createSimpleUpdateWatcher('age_protect');
1654
1655         $scope.floating_list = [];
1656         itemSvc.get_floating_groups().then(function(list){
1657             $scope.floating_list = list;
1658         });
1659         createSimpleUpdateWatcher('floating');
1660
1661         createSimpleUpdateWatcher('circ_lib');
1662         createSimpleUpdateWatcher('circulate');
1663         createSimpleUpdateWatcher('holdable');
1664         createSimpleUpdateWatcher('fine_level');
1665         createSimpleUpdateWatcher('loan_duration');
1666         createSimpleUpdateWatcher('price');
1667         createSimpleUpdateWatcher('cost');
1668         createSimpleUpdateWatcher('deposit');
1669         createSimpleUpdateWatcher('deposit_amount');
1670         createSimpleUpdateWatcher('mint_condition');
1671         createSimpleUpdateWatcher('opac_visible');
1672         createSimpleUpdateWatcher('ref');
1673         createSimpleUpdateWatcher('alert_message');
1674
1675         $scope.saveCompletedCopies = function (and_exit) {
1676             var cnHash = {};
1677             var perCnCopies = {};
1678             angular.forEach( $scope.completed_copies, function (cp) {
1679                 var cn = cp.call_number();
1680                 var cn_cps = cp.call_number().copies();
1681                 cp.call_number().copies([]);
1682                 var cn_id = cp.call_number().id();
1683                 cp.call_number(cn_id); // prevent loops in JSON-ification
1684                 if (!cnHash[cn_id]) {
1685                     cnHash[cn_id] = egCore.idl.Clone(cn);
1686                     perCnCopies[cn_id] = [egCore.idl.Clone(cp)];
1687                 } else {
1688                     perCnCopies[cn_id].push(egCore.idl.Clone(cp));
1689                 }
1690                 cp.call_number(cn); // put the data back
1691                 cp.call_number().copies(cn_cps);
1692                 if (typeof cnHash[cn_id].prefix() == 'object')
1693                     cnHash[cn_id].prefix(cnHash[cn_id].prefix().id()); // un-object-ize some fields
1694                 if (typeof cnHash[cn_id].suffix() == 'object')
1695                     cnHash[cn_id].suffix(cnHash[cn_id].suffix().id()); // un-object-ize some fields
1696             });
1697
1698             angular.forEach(perCnCopies, function (v, k) {
1699                 cnHash[k].copies(v);
1700             });
1701
1702             cnList = [];
1703             angular.forEach(cnHash, function (v, k) {
1704                 cnList.push(v);
1705             });
1706
1707             egNet.request(
1708                 'open-ils.cat',
1709                 'open-ils.cat.asset.volume.fleshed.batch.update.override',
1710                 egCore.auth.token(), cnList, 1, { auto_merge_vols : 1, create_parts : 1, return_copy_ids : 1 }
1711             ).then(function(copy_ids) {
1712                 if (and_exit) {
1713                     $scope.dirty = false;
1714                     if ($scope.defaults.print_item_labels) {
1715                         egCore.net.request(
1716                             'open-ils.actor',
1717                             'open-ils.actor.anon_cache.set_value',
1718                             null, 'print-labels-these-copies', {
1719                                 copies : copy_ids
1720                             }
1721                         ).then(function(key) {
1722                             if (key) {
1723                                 var url = egCore.env.basePath + 'cat/printlabels/' + key;
1724                                 $timeout(function() { $window.open(url, '_blank') }).then(
1725                                     function() { $timeout(function(){$window.close()}); }
1726                                 );
1727                             } else {
1728                                 alert('Could not create anonymous cache key!');
1729                             }
1730                         });
1731                     } else {
1732                         $timeout(function(){$window.close()});
1733                     }
1734                 }
1735             });
1736         }
1737
1738         $scope.saveAndContinue = function () {
1739             $scope.saveCompletedCopies(false);
1740         }
1741
1742         $scope.workingSaveAndExit = function () {
1743             $scope.workingToComplete();
1744             $scope.saveAndExit();
1745         }
1746
1747         $scope.saveAndExit = function () {
1748             $scope.saveCompletedCopies(true);
1749         }
1750
1751     }
1752
1753     $scope.copy_notes_dialog = function(copy_list) {
1754         var default_pub = Boolean($scope.defaults.copy_notes_pub);
1755         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1756
1757         return $uibModal.open({
1758             templateUrl: './cat/volcopy/t_copy_notes',
1759             backdrop: 'static',
1760             animation: true,
1761             controller:
1762                    ['$scope','$uibModalInstance',
1763             function($scope , $uibModalInstance) {
1764                 $scope.focusNote = true;
1765                 $scope.note = {
1766                     creator : egCore.auth.user().id(),
1767                     title   : '',
1768                     value   : '',
1769                     pub     : default_pub,
1770                 };
1771
1772                 $scope.require_initials = false;
1773                 egCore.org.settings([
1774                     'ui.staff.require_initials.copy_notes'
1775                 ]).then(function(set) {
1776                     $scope.require_initials = Boolean(set['ui.staff.require_initials.copy_notes']);
1777                 });
1778
1779                 $scope.note_list = [];
1780                 if (copy_list.length == 1) {
1781                     $scope.note_list = copy_list[0].notes();
1782                 }
1783
1784                 $scope.ok = function(note) {
1785
1786                     if ($scope.initials) {
1787                         note.value = egCore.strings.$replace(
1788                             egCore.strings.COPY_NOTE_INITIALS, {
1789                             value : note.value, 
1790                             initials : $scope.initials,
1791                             ws_ou : egCore.org.get(
1792                                 egCore.auth.user().ws_ou()).shortname()
1793                         });
1794                     }
1795
1796                     angular.forEach(copy_list, function (cp) {
1797                         if (!angular.isArray(cp.notes())) cp.notes([]);
1798                         var n = new egCore.idl.acpn();
1799                         n.isnew(1);
1800                         n.creator(note.creator);
1801                         n.pub(note.pub);
1802                         n.title(note.title);
1803                         n.value(note.value);
1804                         n.owning_copy(cp.id());
1805                         cp.notes().push( n );
1806                     });
1807
1808                     $uibModalInstance.close();
1809                 }
1810
1811                 $scope.cancel = function($event) {
1812                     $uibModalInstance.dismiss();
1813                     $event.preventDefault();
1814                 }
1815             }]
1816         });
1817     }
1818
1819     $scope.copy_tags_dialog = function(copy_list) {
1820         if (!angular.isArray(copy_list)) copy_list = [copy_list];
1821
1822         return $uibModal.open({
1823             templateUrl: './cat/volcopy/t_copy_tags',
1824             backdrop: 'static',
1825             animation: true,
1826             controller:
1827                    ['$scope','$uibModalInstance',
1828             function($scope , $uibModalInstance) {
1829
1830                 $scope.tag_map = [];
1831                 var tag_hash = {};
1832                 var shared_tags = {};
1833                 angular.forEach(copy_list, function (cp) {
1834                     angular.forEach(cp.tags(), function(tag) {
1835                         if (!(tag.tag().id() in shared_tags)) {
1836                             shared_tags[tag.tag().id()] = 1;
1837                         } else {
1838                             shared_tags[tag.tag().id()]++;
1839                         }
1840                         if (!(tag.tag().id() in tag_hash)) {
1841                             tag_hash[tag.tag().id()] = tag;
1842                         }
1843                     });
1844                 });
1845                 angular.forEach(tag_hash, function(value, key) {
1846                     if (shared_tags[key] == copy_list.length) {
1847                         $scope.tag_map.push(value);
1848                     }
1849                 });
1850
1851                 $scope.tag_types = [];
1852                 egCore.pcrud.retrieveAll('cctt', {order_by : { cctt : 'label' }}, {atomic : true}).then(function(list) {
1853                     $scope.tag_types = list;
1854                     $scope.tag_type = $scope.tag_types[0].code(); // just pick a default
1855                 });
1856
1857                 $scope.getTags = function(val) {
1858                     return egCore.pcrud.search('acpt',
1859                         { 
1860                             owner :  egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1861                             label : { 'startwith' : {
1862                                         transform: 'evergreen.lowercase',
1863                                         value : [ 'evergreen.lowercase', val ]
1864                                     }},
1865                             tag_type : $scope.tag_type
1866                         },
1867                         { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1868                     ).then(function(list) {
1869                         return list.map(function(item) {
1870                             return item.label();
1871                         });
1872                     });
1873                 }
1874
1875                 $scope.addTag = function() {
1876                     var tagLabel = $scope.selectedLabel;
1877                     // clear the typeahead
1878                     $scope.selectedLabel = "";
1879
1880                     // first, check tags already associated with the copy
1881                     var foundMatch = false;
1882                     angular.forEach($scope.tag_map, function(tag) {
1883                         if (tag.tag().label() ==  tagLabel && tag.tag().tag_type() == $scope.tag_type) {
1884                             foundMatch = true;
1885                             if (tag.isdeleted()) tag.isdeleted(0); // just deleting the mapping
1886                         }
1887                     });
1888                     if (!foundMatch) {
1889                         egCore.pcrud.search('acpt',
1890                             { 
1891                                 owner : egCore.org.fullPath(egCore.auth.user().ws_ou(), true),
1892                                 label : tagLabel,
1893                                 tag_type : $scope.tag_type
1894                             },
1895                             { order_by : { 'acpt' : ['label'] } }, { atomic: true }
1896                         ).then(function(list) {
1897                             if (list.length > 0) {
1898                                 var newMap = new egCore.idl.acptcm();
1899                                 newMap.isnew(1);
1900                                 newMap.copy(copy_list[0].id());
1901                                 newMap.tag(egCore.idl.Clone(list[0]));
1902                                 $scope.tag_map.push(newMap);
1903                             } else {
1904                                 var newTag = new egCore.idl.acpt();
1905                                 newTag.isnew(1);
1906                                 newTag.owner(egCore.auth.user().ws_ou());
1907                                 newTag.label(tagLabel);
1908                                 newTag.pub('t');
1909                                 newTag.tag_type($scope.tag_type);
1910
1911                                 var newMap = new egCore.idl.acptcm();
1912                                 newMap.isnew(1);
1913                                 newMap.copy(copy_list[0].id());
1914                                 newMap.tag(newTag);
1915                                 $scope.tag_map.push(newMap);
1916                             }
1917                         });
1918                     }
1919                 }
1920
1921                 $scope.ok = function(note) {
1922                     // in the multi-item case, this works OK for
1923                     // adding new maps to existing tags, but doesn't handle
1924                     // all possibilities
1925                     angular.forEach(copy_list, function (cp) {
1926                         cp.tags($scope.tag_map);
1927                     });
1928                     $uibModalInstance.close();
1929                 }
1930
1931                 $scope.cancel = function($event) {
1932                     $uibModalInstance.dismiss();
1933                     $event.preventDefault();
1934                 }
1935             }]
1936         });
1937     }
1938
1939 }])
1940
1941 .directive("egVolTemplate", function () {
1942     return {
1943         restrict: 'E',
1944         replace: true,
1945         template: '<div ng-include="'+"'/eg/staff/cat/volcopy/t_attr_edit'"+'"></div>',
1946         scope: {
1947             editTemplates: '=',
1948         },
1949         controller : ['$scope','$window','itemSvc','egCore','ngToast',
1950             function ( $scope , $window , itemSvc , egCore , ngToast) {
1951
1952                 $scope.i18n = egCore.i18n;
1953
1954                 $scope.defaults = { // If defaults are not set at all, allow everything
1955                     barcode_checkdigit : false,
1956                     auto_gen_barcode : false,
1957                     statcats : true,
1958                     copy_notes : true,
1959                     copy_tags : true,
1960                     attributes : {
1961                         status : true,
1962                         loan_duration : true,
1963                         fine_level : true,
1964                         cost : true,
1965                         alerts : true,
1966                         deposit : true,
1967                         deposit_amount : true,
1968                         opac_visible : true,
1969                         price : true,
1970                         circulate : true,
1971                         mint_condition : true,
1972                         circ_lib : true,
1973                         ref : true,
1974                         circ_modifier : true,
1975                         circ_as_type : true,
1976                         location : true,
1977                         holdable : true,
1978                         age_protect : true,
1979                         floating : true
1980                     }
1981                 };
1982
1983                 $scope.fetchDefaults = function () {
1984                     egCore.hatch.getItem('cat.copy.defaults').then(function(t) {
1985                         if (t) {
1986                             $scope.defaults = t;
1987                             $scope.working.statcat_filter = $scope.defaults.statcat_filter;
1988                             if (
1989                                     typeof $scope.defaults.statcat_filter == 'object' &&
1990                                     Object.keys($scope.defaults.statcat_filter).length > 0
1991                                 ) {
1992                                 // want fieldmapper object here...
1993                                 $scope.defaults.statcat_filter =
1994                                     egCore.idl.Clone($scope.defaults.statcat_filter);
1995                                 // ... and ID here
1996                                 $scope.working.statcat_filter = $scope.defaults.statcat_filter.id();
1997                             }
1998                         }
1999                     });
2000                 }
2001                 $scope.fetchDefaults();
2002
2003                 $scope.dirty = false;
2004                 $scope.$watch('dirty',
2005                     function(newVal, oldVal) {
2006                         if (newVal && newVal != oldVal) {
2007                             $($window).on('beforeunload.template', function(){
2008                                 return 'There is unsaved template data!'
2009                             });
2010                         } else {
2011                             $($window).off('beforeunload.template');
2012                         }
2013                     }
2014                 );
2015
2016                 $scope.template_controls = true;
2017
2018                 $scope.fetchTemplates = function () {
2019                     itemSvc.get_acp_templates().then(function(t) {
2020                         if (t) {
2021                             $scope.templates = t;
2022                             $scope.template_name_list = Object.keys(t).sort();
2023                         }
2024                     });
2025                 }
2026                 $scope.fetchTemplates();
2027             
2028                 $scope.applyTemplate = function (n) {
2029                     angular.forEach($scope.templates[n], function (v,k) {
2030                         if (k == 'circ_lib') {
2031                             $scope.working[k] = egCore.org.get(v);
2032                         } else if (!angular.isObject(v)) {
2033                             $scope.working[k] = angular.copy(v);
2034                         } else {
2035                             angular.forEach(v, function (sv,sk) {
2036                                 if (!(k in $scope.working))
2037                                     $scope.working[k] = {};
2038                                 $scope.working[k][sk] = angular.copy(sv);
2039                             });
2040                         }
2041                     });
2042                     $scope.template_name = '';
2043                 }
2044
2045                 $scope.deleteTemplate = function (n) {
2046                     if (n) {
2047                         delete $scope.templates[n]
2048                         $scope.template_name_list = Object.keys($scope.templates).sort();
2049                         $scope.template_name = '';
2050                         itemSvc.save_acp_templates($scope.templates);
2051                         $scope.$parent.fetchTemplates();
2052                         ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_DELETE);
2053                     }
2054                 }
2055
2056                 $scope.saveTemplate = function (n) {
2057                     if (n) {
2058                         var tmpl = {};
2059             
2060                         angular.forEach($scope.working, function (v,k) {
2061                             if (angular.isObject(v)) { // we'll use the pkey
2062                                 if (v.id) v = v.id();
2063                                 else if (v.code) v = v.code();
2064                             }
2065             
2066                             tmpl[k] = v;
2067                         });
2068             
2069                         $scope.templates[n] = tmpl;
2070                         $scope.template_name_list = Object.keys($scope.templates).sort();
2071             
2072                         itemSvc.save_acp_templates($scope.templates);
2073                         $scope.$parent.fetchTemplates();
2074
2075                         $scope.dirty = false;
2076                     } else {
2077                         // save all templates, as we might do after an import
2078                         itemSvc.save_acp_templates($scope.templates);
2079                         $scope.$parent.fetchTemplates();
2080                     }
2081                     ngToast.create(egCore.strings.VOL_COPY_TEMPLATE_SUCCESS_SAVE);
2082                 }
2083             
2084                 $scope.templates = {};
2085                 $scope.imported_templates = { data : '' };
2086                 $scope.template_name = '';
2087                 $scope.template_name_list = [];
2088
2089                 $scope.$watch('imported_templates.data', function(newVal, oldVal) {
2090                     if (newVal && newVal != oldVal) {
2091                         try {
2092                             var newTemplates = JSON.parse(newVal);
2093                             if (!Object.keys(newTemplates).length) return;
2094                             angular.forEach(Object.keys(newTemplates), function (k) {
2095                                 $scope.templates[k] = newTemplates[k];
2096                             });
2097                             itemSvc.save_acp_templates($scope.templates);
2098                             $scope.fetchTemplates();
2099                         } catch (E) {
2100                             console.log('tried to import an invalid copy template file');
2101                         }
2102                     }
2103                 });
2104
2105                 $scope.tracker = function (x,f) { if (x) return x[f]() };
2106                 $scope.idTracker = function (x) { if (x) return $scope.tracker(x,'id') };
2107                 $scope.cant_have_vols = function (id) { return !egCore.org.CanHaveVolumes(id); };
2108             
2109                 $scope.orgById = function (id) { return egCore.org.get(id) }
2110                 $scope.statusById = function (id) {
2111                     return $scope.status_list.filter( function (s) { return s.id() == id } )[0];
2112                 }
2113                 $scope.locationById = function (id) {
2114                     return $scope.location_cache[''+id];
2115                 }
2116             
2117                 createSimpleUpdateWatcher = function (field) {
2118                     $scope.$watch('working.' + field, function () {
2119                         var newval = $scope.working[field];
2120             
2121                         if (typeof newval != 'undefined') {
2122                             $scope.dirty = true;
2123                             if (angular.isObject(newval)) { // we'll use the pkey
2124                                 if (newval.id) $scope.working[field] = newval.id();
2125                                 else if (newval.code) $scope.working[field] = newval.code();
2126                             }
2127             
2128                             if (""+newval == "" || newval == null) {
2129                                 $scope.working[field] = undefined;
2130                             }
2131             
2132                         }
2133                     });
2134                 }
2135             
2136                 $scope.working = {
2137                     statcats: {},
2138                     statcat_filter: undefined
2139                 };
2140             
2141                 $scope.statcat_visible = function (sc_owner) {
2142                     var visible = typeof $scope.working.statcat_filter === 'undefined' || !$scope.working.statcat_filter;
2143                     angular.forEach(egCore.org.ancestors(sc_owner), function (ancestor_org) {
2144                         if ($scope.working.statcat_filter == ancestor_org.id())
2145                             visible = true;
2146                     });
2147                     return visible;
2148                 }
2149
2150                 createStatcatUpdateWatcher = function (id) {
2151                     return $scope.$watch('working.statcats[' + id + ']', function () {
2152                         if ($scope.working.statcats) {
2153                             var newval = $scope.working.statcats[id];
2154                 
2155                             if (typeof newval != 'undefined') {
2156                                 $scope.dirty = true;
2157                                 if (angular.isObject(newval)) { // we'll use the pkey
2158                                     newval = newval.id();
2159                                 }
2160                 
2161                                 if (""+newval == "" || newval == null) {
2162                                     $scope.working.statcats[id] = undefined;
2163                                     newval = null;
2164                                 }
2165                 
2166                             }
2167                         }
2168                     });
2169                 }
2170
2171                 $scope.clearWorking = function () {
2172                     angular.forEach($scope.working, function (v,k,o) {
2173                         if (!angular.isObject(v)) {
2174                             if (typeof v != 'undefined')
2175                                 $scope.working[k] = undefined;
2176                         } else if (k != 'circ_lib') {
2177                             angular.forEach(v, function (sv,sk) {
2178                                 $scope.working[k][sk] = undefined;
2179                             });
2180                         }
2181                     });
2182                     $scope.working.circ_lib = undefined; // special
2183                     $scope.dirty = false;
2184                 }
2185
2186                 $scope.working = {};
2187                 $scope.location_orgs = [];
2188                 $scope.location_cache = {};
2189             
2190                 $scope.location_list = [];
2191                 itemSvc.get_locations(
2192                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2193                 ).then(function(list){
2194                     $scope.location_list = list;
2195                 });
2196                 createSimpleUpdateWatcher('location');
2197
2198                 $scope.statcat_filter_list = egCore.org.fullPath( egCore.auth.user().ws_ou() );
2199
2200                 $scope.statcats = [];
2201                 itemSvc.get_statcats(
2202                     egCore.org.fullPath( egCore.auth.user().ws_ou(), true )
2203                 ).then(function(list){
2204                     $scope.statcats = list;
2205                     angular.forEach($scope.statcats, function (s) {
2206
2207                         if (!$scope.working)
2208                             $scope.working = { statcats: {}, statcat_filter: undefined};
2209                         if (!$scope.working.statcats)
2210                             $scope.working.statcats = {};
2211
2212                         $scope.working.statcats[s.id()] = undefined;
2213                         createStatcatUpdateWatcher(s.id());
2214                     });
2215                 });
2216             
2217                 $scope.status_list = [];
2218                 itemSvc.get_magic_statuses().then(function(list){
2219                     $scope.magic_status_list = list;
2220                 });
2221                 itemSvc.get_statuses().then(function(list){
2222                     $scope.status_list = list;
2223                 });
2224                 createSimpleUpdateWatcher('status');
2225             
2226                 $scope.circ_modifier_list = [];
2227                 itemSvc.get_circ_mods().then(function(list){
2228                     $scope.circ_modifier_list = list;
2229                 });
2230                 createSimpleUpdateWatcher('circ_modifier');
2231             
2232                 $scope.circ_type_list = [];
2233                 itemSvc.get_circ_types().then(function(list){
2234                     $scope.circ_type_list = list;
2235                 });
2236                 createSimpleUpdateWatcher('circ_as_type');
2237             
2238                 $scope.age_protect_list = [];
2239                 itemSvc.get_age_protects().then(function(list){
2240                     $scope.age_protect_list = list;
2241                 });
2242                 createSimpleUpdateWatcher('age_protect');
2243             
2244                 createSimpleUpdateWatcher('circulate');
2245                 createSimpleUpdateWatcher('holdable');
2246                 createSimpleUpdateWatcher('fine_level');
2247                 createSimpleUpdateWatcher('loan_duration');
2248                 createSimpleUpdateWatcher('cost');
2249                 createSimpleUpdateWatcher('deposit');
2250                 createSimpleUpdateWatcher('deposit_amount');
2251                 createSimpleUpdateWatcher('mint_condition');
2252                 createSimpleUpdateWatcher('opac_visible');
2253                 createSimpleUpdateWatcher('ref');
2254                 createSimpleUpdateWatcher('alert_message');
2255
2256                 $scope.suffix_list = [];
2257                 itemSvc.get_suffixes(egCore.auth.user().ws_ou()).then(function(list){
2258                     $scope.suffix_list = list;
2259                 });
2260
2261                 $scope.prefix_list = [];
2262                 itemSvc.get_prefixes(egCore.auth.user().ws_ou()).then(function(list){
2263                     $scope.prefix_list = list;
2264                 });
2265
2266                 $scope.classification_list = [];
2267                 itemSvc.get_classifications().then(function(list){
2268                     $scope.classification_list = list;
2269                 });
2270
2271                 createSimpleUpdateWatcher('working.callnumber.classification');
2272                 createSimpleUpdateWatcher('working.callnumber.prefix');
2273                 createSimpleUpdateWatcher('working.callnumber.suffix');
2274             }
2275         ]
2276     }
2277 })
2278
2279