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