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