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