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