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