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