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