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