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