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