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