]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/offline.js
LP#1706124: Make include inactive patrons checkbox sticky
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / offline.js
1 /**
2  * App to drive the offline UI
3  */
4
5 lf.isOffline = true;
6
7 angular.module('egOffline', ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'ngToast', 'tableSort'])
8
9 .config(
10        ['$routeProvider','$locationProvider','$compileProvider',
11 function($routeProvider , $locationProvider , $compileProvider) {
12
13     $locationProvider.html5Mode(true);
14     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/);
15
16     /**
17      * Route resolvers allow us to run async commands
18      * before the page controller is instantiated.
19      */
20     var resolver = {delay : ['egCore', 
21         function(egCore) {
22             return egCore.startup.go();
23         }
24     ]};
25
26     $routeProvider.when('/offline-interface/:tab', {
27         templateUrl: 'offline-template',
28         controller: 'OfflineCtrl',
29         resolve : resolver
30     });
31
32     // default page 
33     $routeProvider.otherwise({
34         templateUrl : 'offline-template',
35         controller : 'OfflineCtrl',
36         resolve : resolver
37     });
38 }])
39
40 .controller('OfflineSessionCtrl', 
41            ['$scope','$window','egCore','$routeParams','$http','$q','$timeout','egPromptDialog','ngToast','egProgressDialog',
42     function($scope , $window , egCore , $routeParams , $http , $q , $timeout , egPromptDialog , ngToast , egProgressDialog) {
43         $scope.active_session_tab = 'pending';
44
45         $scope.lookupNoncatTypeName = function (type) {
46             var nc =  $scope.noncats.filter(function(n){ return n.id() == type })[0];
47             if (nc) return nc.name();
48             return '';
49         }
50
51         $scope.createDate = function (ts, epoch) {
52             if (!ts) return '';
53             if (epoch) ts = ts * 1000;
54             return new Date(ts);
55         }
56
57         $scope.setSession = function (s, ind) {
58             $scope.current_session = s;
59             $scope.current_session_index = ind;
60
61             return $scope.refreshExceptions(s);
62         }
63
64         $scope.createSession = function () {
65
66             return egPromptDialog.open(
67                 egCore.strings.OFFLINE_SESSION_DESC, '',
68                 {ok : function(value) {
69                     if (value) {
70
71                         return $http.get(formURL({action:'create',desc:value})).then(function(res) {
72                             if (res.data.ilsevent == "0") return $q.when(res.data.payload);
73                             return $q.reject();
74                         }).then(function (seskey) {
75                             return $scope.refreshSessions().then(function() {
76                                 if (seskey) {
77                                     var s = $scope.sessions.filter(function(s){ s.key == seskey })[0];
78                                     var ind = $scope.sessions.length - 1; // sorted by create time, so new one is last
79                                     return $scope.setSession(s, ind);
80                                 }
81                             });
82                         }, function() {
83                             ngToast.warning(egCore.strings.OFFLINE_SESSION_CREATE_FAILED);
84                         });
85                     }
86                 }}
87             );
88         }
89
90         $scope.processSession = function (s, ind) {
91             return $scope.setSession(s, ind).then(function() {
92                 egProgressDialog.open();
93
94                 return $http.get(
95                     formURL({action:'execute',seskey:$scope.current_session.key})
96                 ).then(function(res) {
97                     if (res.data.ilsevent == "0") return $q.when(res.data.payload);
98                     return $q.reject();
99                 }).then(function () {
100                     egProgressDialog.close();
101                     return $scope.refreshSessions()
102                         .then(function(){ return $scope.refreshExceptions(s) });
103                 },function () {
104                     egProgressDialog.close();
105                     return $scope.refreshSessions().then(function() {
106                         ngToast.warning(egCore.strings.OFFLINE_SESSION_PROCESSING_FAILED);
107                     });
108                 });
109             });
110         }
111
112         $scope.refreshExceptions = function (s) {
113             return $http.get(
114                 formURL({
115                     action      : 'status',
116                     status_type : 'exceptions',
117                     seskey      : s.key
118                 })
119             ).then(function(res) {
120                 if (res.data.ilsevent) {
121                     $scope.current_session.exceptions = [];
122                 } else {
123                     $scope.current_session.exceptions = res.data;
124                 }
125                 return $q.when();
126             });
127         }
128
129         $scope.refreshSessions = function () {
130
131             return $http.get(formURL({action:'status',status_type:'sessions'})).then(function(res) {
132                 if (res.data) {
133                     $scope.sessions = res.data;
134                     return $q.when();
135                 }
136                 return $q.reject();
137             }).then(function() {
138                 var creator_list = [$q.when()];
139                 angular.forEach($scope.sessions, function (s) {
140                     s.total = 0;
141                     s.org = egCore.org.get(s.org).shortname();
142                     creator_list.push(egCore.pcrud.retrieve('au',s.creator).then(function(u) {
143                         s.creator = u.family_name();
144                     }));
145                     angular.forEach(s.scripts, function(sc) {
146                         s.total += sc.count;
147                     });
148                 });
149
150                 return $q.all(creator_list);
151             });
152         }
153
154         $scope.reprintLast = function () {
155             egCore.print.reprintLast();
156         }
157
158
159         $scope.uploadPending = function (s, ind) {
160             return $scope.setSession(s, ind).then(function() {
161
162                 egProgressDialog.open();
163                 return $scope.createOfflineXactBlob().then(function(blob) {
164
165                     var form = new FormData();
166                     form.append("ses", egCore.auth.token());
167                     form.append("org", $scope.org.id());
168                     form.append("ws", $scope.current_workstation_name());
169                     form.append("wc", 1);
170                     form.append("action", "load");
171                     form.append("seskey", $scope.current_session.key);
172                     form.append("file", blob, "file");
173
174                     return $http.post(
175                         '/cgi-bin/offline/offline.pl?' + new Date().getTime(),
176                         form,
177                         {
178                             transformRequest: angular.identity,
179                             headers: {'Content-Type': undefined}
180                         }
181                     ).then(function(res) {
182                         egProgressDialog.close();
183                         if (res.data.ilsevent == "0") {
184                             return $scope.clear_pending(true).then(function() {
185                                 return $scope.refreshSessions();
186                             });
187                         } else {
188                             ngToast.warning(egCore.strings.OFFLINE_SESSION_UPLOAD_FAILED);
189                             return $scope.refreshSessions();
190                         }
191                     },function () { egProgressDialog.close() });
192                 });
193             });
194         }
195
196         $scope.retrieveDetails = function (x) {
197             alert(JSON.stringify(x, null, 2)); // egAlertDialog kills pretty printing
198         }
199
200         $scope.retrieveItem = function (bc) {
201             return egCore.pcrud.search('acp',{deleted: 'f', barcode: bc}).then(function(copy) {
202                 if (copy) {
203                     return $window.open(
204                         egCore.env.basePath +
205                         '/cat/item/' + copy.id(),
206                         '_blank'
207                     ).focus();
208                 }
209
210                 ngToast.warning(egCore.strings.ITEM_NOT_FOUND);
211             });
212         }
213
214         $scope.retrievePatron = function (bc) {
215             return egCore.pcrud.search('ac',{barcode: bc}).then(function(card) {
216                 if (card) {
217                     return $window.open(
218                         egCore.env.basePath +
219                         '/circ/patron/' + card.usr() + '/checkout',
220                         '_blank'
221                     ).focus();
222                 }
223
224                 ngToast.warning(egCore.strings.PATRON_NOT_FOUND);
225             });
226         }
227
228         function formURL (params) {
229             var url = '/cgi-bin/offline/offline.pl?' + new Date().getTime();
230
231             var defaults = {
232                 org : $scope.org ? $scope.org.id() : null,
233                 ws  : $scope.current_workstation_name(),
234                 wc  : 1,
235                 ses : egCore.auth.token()
236             }
237
238             angular.extend(params, defaults)
239
240             var first = true;
241             for (var k in params) {
242                 url += '&' + k + '=' + window.encodeURIComponent(params[k]);
243             }
244             return url;
245         }
246
247         $scope.$watch('org',function(n){if (n) $scope.refreshSessions()});
248
249     }
250 ])
251
252 .controller('OfflineCtrl', 
253            ['$q','$scope','$window','$location','$rootScope','egCore','egLovefield','$routeParams','$timeout','$http','ngToast','egConfirmDialog','egUnloadPrompt',
254     function($q , $scope , $window , $location , $rootScope , egCore , egLovefield , $routeParams , $timeout , $http , ngToast , egConfirmDialog , egUnloadPrompt) {
255
256         // Immediately redirect if we're really offline
257         if (!$window.navigator.onLine) {
258             if ($location.path().match(/session$/)) {
259                 var path = $location.path();
260                 console.log('internal redirect');
261                 return $location.path(path.replace('session','checkout'));
262             }
263         }
264
265         var today = new Date();
266         today.setHours(0);
267         today.setMinutes(0);
268         today.setSeconds(0);
269         today.setMilliseconds(0);
270
271         $scope.minDate = today;
272         $scope.blocked_patron = null;
273         $scope.bad_barcode = null;
274         $scope.barcode_type = 'barcode';
275         $scope.focusMe = true;
276         $scope.shared = { outOfRange : false, due_date : null, due_date_offset : '' };
277         $scope.workstation_obj = null;
278         $scope.workstation = '';
279         $scope.workstation_owner = '';
280         $scope.workstations = [];
281         $scope.org = null;
282         $scope.do_print = Boolean($scope.active_tab == 'checkout');
283         $scope.do_print_changed = false;
284         $scope.printed = false;
285
286         $scope.imported_pending_xacts = { data : '' };
287
288         $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
289         $scope.all_xact = [];
290         $scope.noncats = [];
291
292         $scope.checkout = { noncat_type : '' };
293         $scope.renew = { noncat_type : '' };
294         $scope.in_house_use = {count : 1};
295         $scope.checkin = { backdate : new Date() };
296
297         $scope.current_workstation_owning_lib = function () {
298             return $scope.workstations.filter(function(w) {
299                 return $scope.workstation == w.id
300             })[0].owning_lib;
301         }
302
303         $scope.current_workstation_name = function () {
304             return $scope.workstations.filter(function(w) {
305                 return $scope.workstation == w.id
306             })[0].name;
307         }
308
309         $scope.$watch('workstation', function (n,o) {
310             if (egCore.env.aou)
311                 $scope.org = egCore.org.get($scope.current_workstation_owning_lib());
312         });
313
314         $scope.changeCheck = function () {
315             $scope.strict_barcode = !$scope.strict_barcode;
316             $scope.do_check_changed = true;
317             egCore.hatch.setItem('eg.offline.strict_barcode', $scope.strict_barcode)
318         }
319
320         $scope.changePrint = function () {
321             $scope.do_print = !$scope.do_print;
322             $scope.do_print_changed = true;
323             egCore.hatch.setItem('eg.offline.print_receipt', $scope.do_print)
324         }
325
326         $scope.logged_in = egCore.auth.token() ? true : false;
327
328
329         $scope.active_tab = $routeParams.tab;
330         $timeout(function(){
331             if (!$scope.logged_in) {
332                 $scope.active_tab = 'checkout';
333             } else {
334                 $scope.active_tab = 'session';
335             }
336         });
337         
338         egCore.hatch.getItem('eg.offline.print_receipt')
339         .then(function(setting) {
340             $scope.do_print = setting;
341             if (setting !== undefined) $scope.do_print_changed = true;
342         });
343
344         egCore.hatch.getItem('eg.offline.strict_barcode')
345         .then(function(setting) {
346             $scope.strict_barcode = setting;
347             if (setting !== undefined) $scope.do_check_changed = true;
348         });
349
350         egCore.hatch.getItem('eg.workstation.all')
351         .then(function(all) {
352             if (all && all.length) {
353                 $scope.workstations = all;
354
355                 if (ws = $location.search().ws) {
356                     // user requested a workstation via URL
357                     var match = all.filter(
358                         function(w) {return ws == w.name} )[0];
359
360                     if (match) {
361                         // requested WS registered on this client
362                         $scope.workstation = match.id;
363                     } else {
364                         // the requested WS is not registered on this client
365                         $scope.wsNotRegistered = true;
366                     }
367                 } else {
368                     // no workstation requested; use the default
369                     egCore.hatch.getItem('eg.workstation.default')
370                     .then(function(ws) {
371                         var ws_obj = all.filter(function(w) {
372                             return ws == w.name
373                         })[0];
374
375                         $scope.workstation_obj = ws_obj;
376                         $scope.workstation = ws_obj.id;
377                         $scope.workstation_owner = ws_obj.owning_lib;
378
379                         return egLovefield.reconstituteList('cnct').then(function () {
380                             $scope.noncats = egCore.env.cnct.list;
381                         });
382                     });
383                 }
384             } 
385         });
386
387         $scope.downloadBlockList = function () {
388             var url = '/standalone/list.txt?ses='
389                 + egCore.auth.token()
390                 + '&' + new Date().getTime();
391             return $http.get(url).then(
392                 function (res) {
393                     if (res.data) {
394                         var lines = res.data.split('\n');
395                         egLovefield.destroyOfflineBlocks().then(function(){
396                             angular.forEach(lines, function (l) {
397                                 var parts = l.split(' ');
398                                 egLovefield.addOfflineBlock(parts[0], parts[1]);
399                             });
400                             return $q.when();
401                         }).then(function(){
402                             ngToast.create(egCore.strings.OFFLINE_BLOCKLIST_SUCCESS);
403                         });
404                     }
405                 },function(){
406                     ngToast.warning(egCore.strings.OFFLINE_BLOCKLIST_FAIL);
407                     egCore.audio.play('warning.offline.blocklist_fail');
408                 }
409             );
410         }
411
412         $scope.createOfflineXactBlob = function () {
413             return egLovefield.retrievePendingOfflineXacts().then(function(list) {
414                 var flat_list = [];
415                 angular.forEach(list, function (i) {
416                     flat_list.push(JSON.stringify(i) + '\n');
417                 });
418
419                 var blob = new Blob(flat_list, {type: 'text/plain'});
420
421                 return $q.when(blob)
422             });
423         }
424
425         $scope.pending_xacts = [];
426         $scope.retrieve_pending = function () {
427             return egLovefield.retrievePendingOfflineXacts().then(function(list) {
428                 $scope.pending_xacts = list;
429                 return $q.when(list);
430             });
431         }
432
433         $scope.save = function () {
434             var promises = [$q.when()];
435             angular.forEach($scope.all_xact, function (x) {
436                 promises.push(egLovefield.addOfflineXact(x));
437             });
438
439             var prints = [$q.when()];
440             if ($scope.do_print) {
441                 angular.forEach(['checkin','checkout','renew','in_house_use'], function(xtype) {
442                     if ($scope.xact_page[xtype].length > 0) {
443                         prints.push(egCore.print.print({
444                             context : 'offline', 
445                             template : 'offline_'+xtype,
446                             scope : {
447                                 transactions    : $scope.xact_page[xtype]
448                             }
449                         }));
450                     }
451                 });
452             }
453
454             return $q.all(promises.concat(prints)).finally(function() {
455                 egUnloadPrompt.clear();
456                 if (prints.length > 1) $scope.printed = true;
457                 $scope.all_xact = [];
458                 $scope.xact_page = { checkin:[], checkout:[], renew:[], in_house_use:[] };
459                 angular.forEach(['checkout','renew'], function (xtype) {
460                     $scope[xtype].patron_barcode = '';
461                 });
462                 $scope.retrieve_pending();
463             });
464         }
465
466         $rootScope.save_offline_xacts = function () { return $scope.save() };
467         $rootScope.active_tab = function (t) { $scope.active_tab = t };
468
469         $scope.logout = function () {
470             egCore.auth.logout();
471             $window.location.href = location.href;
472         }
473
474         $scope.clear_pending = function (skip_confirm) {
475             if (skip_confirm) {
476                 return egLovefield.destroyPendingOfflineXacts().then(function () {
477                     return $scope.retrieve_pending();
478                 });
479             }
480             return egConfirmDialog.open(
481                 egCore.strings.CONFIRM_CLEAR_PENDING,
482                 egCore.strings.CONFIRM_CLEAR_PENDING_BODY,
483                 {}
484             ).result.then(function() {
485                 return egLovefield.destroyPendingOfflineXacts().then(function () {
486                     return $scope.retrieve_pending();
487                 });
488             });
489
490         }
491
492         $scope.retrieve_pending();
493         $scope.$watch('active_tab', function (n,o) {
494             console.log('watch caught change to active_tab: ' + o + ' -> ' + n);
495             if (n != o && !$scope.do_check_changed && n != 'checkout') $scope.strict_barcode = false;
496             if (n != o && !$scope.do_check_changed && n == 'checkout') $scope.strict_barcode = true;
497             if (n != o && !$scope.do_print_changed && n != 'checkout') $scope.do_print = false;
498             if (n != o && !$scope.do_print_changed && n == 'checkout') $scope.do_print = true;
499             if (n != o && n == 'session') $scope.retrieve_pending();
500         });
501
502         $scope.$watch('imported_pending_xacts.data', function (n, o) {
503             if (n != 0) {
504                 var lines = n.split('\n');
505                 var promises = [];
506
507                 angular.forEach(lines, function (l) {
508                     if (!l) return;
509
510                     try {
511                         promises.push(
512                             egLovefield.addOfflineXact(JSON.parse(l))
513                         );
514                     } catch (err) {
515                         ngToast.warning(err);
516                     }
517                 });
518
519                 $q.all(promises).then(function () { $scope.retrieve_pending() });
520             }
521         });
522
523         $scope.resetDueDate = function (xtype) {
524             $scope.shared.due_date = new Date();
525             $scope.shared.due_date.setDate($scope.shared.due_date.getDate() + parseInt($scope.shared.due_date_offset));
526         }
527
528         $scope.notEnough = function (xtype) {
529
530             if (xtype == 'checkout') {
531                 if ($scope.shared.outOfRange) return true;
532                 if (
533                     $scope.checkout.patron_barcode &&
534                     ($scope.shared.due_date || $scope.shared.due_date_offset) &&
535                     ($scope.checkout.barcode || ($scope.checkout.noncat_type && $scope.checkout.noncat_count))
536                 ) return false;
537                 return true;
538             }
539
540             if (xtype == 'renew') {
541                 if ($scope.shared.outOfRange) return true;
542                 if (
543                     $scope.renew.barcode &&
544                     ($scope.shared.due_date || $scope.shared.due_date_offset)
545                 ) return false;
546                 return true;
547             }
548
549             if (xtype == 'in_house_use') {
550                 if (
551                     $scope.in_house_use.barcode && $scope.in_house_use.count
552                 ) return false;
553                 return true;
554             }
555
556             if (xtype == 'checkin') {
557                 if (
558                     $scope.checkin.barcode && $scope.checkin.backdate
559                 ) return false;
560                 return true;
561             }
562         }
563
564         $scope.clear = function (xtype) {
565             $scope[xtype] = {};
566             if (xtype=="in_house_use") $scope[xtype].count = 1;
567         }
568
569         $scope.add = function (xtype,next_focus) {
570
571             var barcode = $scope[xtype].barcode;
572             if (barcode) {
573                 if ($scope.xact_page[xtype].filter(function(x){ return x.barcode == barcode }).length > 0) {
574                     ngToast.warning(egCore.strings.DUPLICATE_BARCODE);
575                     egCore.audio.play('warning.offline.duplicate_barcode');
576                     $scope[xtype].barcode = '';
577                     if (next_focus) $('#'+next_focus).focus();
578                     return;
579                 }
580             }
581
582             var pbarcode = $scope[xtype].patron_barcode;
583             if (pbarcode) {
584                 egLovefield.testOfflineBlock(pbarcode).then(function (blocked) {
585                     if (blocked) {
586                         egCore.audio.play('warning.offline.blocked_patron');
587                         egConfirmDialog.open(
588                             egCore.strings.PATRON_BLOCKED,
589                             egCore.strings.PATRON_BLOCKED_WHY[blocked],
590                             {}, egCore.strings.ALLOW, egCore.strings.REJECT
591                         ).result.then(
592                             function(){ // forced
593                                 $scope.blocked_patron = null;
594                                 _add_impl(xtype,true)
595                                 if (next_focus) $('#'+next_focus).focus();
596                             },function(){ // stopped
597                                 $scope.blocked_patron = xtype;
598                                 if (next_focus) $('#'+next_focus).focus();
599                                 return;
600                             }
601                         );
602                     } else {
603                         $scope.blocked_patron = null;
604                         _add_impl(xtype,true)
605                         if (next_focus) $('#'+next_focus).focus();
606                     }
607                 });
608             } else {
609                 _add_impl(xtype);
610                 if (next_focus) $('#'+next_focus).focus();
611             }
612         }
613
614         function _add_impl (xtype,digest) {
615             var pbarcode = $scope[xtype].patron_barcode;
616             var backdate = $scope[xtype].backdate;
617
618             if ($scope.strict_barcode && pbarcode) {
619                 if (!check_barcode(pbarcode)) {
620                     $scope.bad_barcode = xtype;
621                     egCore.audio.play('warning.offline.bad_barcode');
622                     return egConfirmDialog.open(
623                         egCore.strings.BAD_PATRON_BARCODE,
624                         egCore.strings.BAD_PATRON_BARCODE_CD,
625                         {}, egCore.strings.ALLOW, egCore.strings.REJECT
626                     ).result.then(
627                         function(){ // forced
628                             $scope.blocked_patron = null;
629                             return _add_impl2(xtype,digest)
630                         },function(){ // stopped
631                             $scope.blocked_patron = xtype;
632                         }
633                     );
634                 }
635             }
636
637             if ($scope.strict_barcode && $scope[xtype].barcode) {
638                 if (!check_barcode($scope[xtype].barcode)) {
639                     $scope.bad_barcode = xtype;
640                     egCore.audio.play('warning.offline.bad_barcode');
641                     return egConfirmDialog.open(
642                         egCore.strings.BAD_BARCODE,
643                         egCore.strings.BAD_BARCODE_CD,
644                         {}, egCore.strings.ALLOW, egCore.strings.REJECT
645                     ).result.then(
646                         function(){ // forced
647                             $scope.blocked_patron = null;
648                             return _add_impl2(xtype,digest)
649                         },function(){ // stopped
650                             $scope.blocked_patron = xtype;
651                         }
652                     );
653                 }
654             }
655
656             return _add_impl2(xtype,digest);
657         }
658
659         function _add_impl2 (xtype,digest) {
660             var pbarcode = $scope[xtype].patron_barcode;
661             var backdate = $scope[xtype].backdate;
662
663             $scope.bad_barcode = null;
664
665             var now = new Date().getTime();
666             now = now / 1000;
667
668             if ($scope[xtype].noncat_type) $scope[xtype].noncat = 1;
669
670             if ($scope.shared.due_date && (xtype == 'checkout' || xtype == 'renew')) {
671                 $scope[xtype].due_date = $scope.shared.due_date.toISOString();
672                 $scope[xtype].checkout_time = new Date().toISOString();
673             }
674
675             var xact = { timestamp : parseInt(now), type : xtype, delta : 0 };
676
677             $scope.xact_page[xtype].push(
678                 angular.extend(xact, $scope[xtype])
679             );
680
681             $scope.all_xact.push(xact)
682             egUnloadPrompt.attach($rootScope);
683
684             $scope[xtype] = {};
685
686             if (pbarcode) $scope[xtype].patron_barcode = pbarcode;
687             if (backdate) $scope[xtype].backdate = backdate;
688             if (xtype=="in_house_use") $scope[xtype].count = 1;
689
690             if (digest) $timeout(function(){$scope.$apply()});
691         }
692
693         check_barcode = function(bc) {
694             if (bc != Number(bc)) return false;
695             bc = bc.toString();
696             // "16.00" == Number("16.00"), but the . is bad.
697             // Throw out any barcode that isn't just digits
698             if (bc.search(/\D/) != -1) return false;
699             var last_digit = bc.substr(bc.length-1);
700             var stripped_barcode = bc.substr(0,bc.length-1);
701             return barcode_checkdigit(stripped_barcode).toString() == last_digit;
702         }
703     
704         barcode_checkdigit = function(bc) {
705             var reverse_barcode = bc.toString().split('').reverse();
706             var check_sum = 0; var multiplier = 2;
707             for (var i = 0; i < reverse_barcode.length; i++) {
708                 var digit = reverse_barcode[i];
709                 var product = digit * multiplier; product = product.toString();
710                 var temp_sum = 0;
711                 for (var j = 0; j < product.length; j++) {
712                     temp_sum += Number( product[j] );
713                 }
714                 check_sum += Number( temp_sum );
715                 multiplier = ( multiplier == 2 ? 1 : 2 );
716             }
717             check_sum = check_sum.toString();
718             var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
719             var check_digit = next_multiple_of_10 - Number(check_sum);
720             if (check_digit == 10) check_digit = 0;
721             return check_digit;
722         }
723
724     }
725 ])
726
727 // dummy service so standalone patron editor can reference it
728 .factory('patronSvc', function() { return { /* dummy */ } })
729
730 .factory('patronRegSvc', ['$q', 'egCore', 'egLovefield', function($q, egCore, egLovefield) {
731
732     egLovefield.isOffline = true;
733
734     var service = {
735         org : null,                // will come from workstation org 
736         field_doc : {},            // config.idl_field_doc
737         profiles : [],             // permission groups
738         edit_profiles : [],        // perm groups we can modify
739         sms_carriers : [],
740         user_settings : {},        // applied user settings
741         user_setting_types : {},   // config.usr_setting_type
742         opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
743         surveys : [],
744         survey_questions : {},
745         survey_answers : {},
746         survey_responses : {},     // survey.responses for loaded patron in progress
747         stat_cats : [],
748         stat_cat_entry_maps : {},   // cat.id to selected value
749         virt_id : -1,               // virtual ID for new objects
750         init_done : false           // have we loaded our initialization data?
751     };
752
753     service.offlineMode = function () {
754         return lf.isOffline;
755     }
756
757     // launch a series of parallel data retrieval calls
758     service.init = function(scope) {
759
760         // Data loaded here only needs to be retrieved the first time this
761         // tab becomes active within the current instance of the patron app.
762         // In other words, navigating between patron tabs will not cause
763         // all of this data to be reloaded.  Navigating to a separate app
764         // and returning will cause the data to be reloaded.
765         if (service.init_done) return $q.when();
766         service.init_done = true;
767
768         return $q.all([
769             service.get_field_doc(),
770             service.get_perm_groups(),
771             service.get_ident_types(),
772             service.get_user_settings(),
773             service.get_org_settings(),
774             service.get_stat_cats(),
775             service.get_surveys(),
776             service.get_net_access_levels()
777         ]);
778     };
779
780     service.get_linked_addr_users = function(addrs) {
781         return $q.when();
782     }
783
784     service.apply_secondary_groups = function(user_id, group_ids) {
785         return $q.when(true);
786     }
787
788     // See note above about not loading egUser.
789     // TODO: i18n
790     service.format_name = function(last, first, middle) {
791         return last + ', ' + first + (middle ? ' ' + middle : '');
792     }
793
794     service.check_dupe_username = function(usrname) {
795         return $q.when(false);
796     }
797
798     // determine which user groups our user is not allowed to modify
799     service.set_edit_profiles = function() {
800         service.edit_profiles = egCore.env.pgt.list.filter(
801             function (p) { return p.application_perm() == 'group_application.user.patron' }
802         );
803         return $q.when;
804     }
805
806     // resolves to a hash of perm-name => boolean value indicating
807     // wether the user has the permission at org_id.
808     service.has_perms_for_org = function(org_id) {
809
810         var perms_needed = [
811             'UPDATE_USER',
812             'CREATE_USER',
813             'CREATE_USER_GROUP_LINK', 
814             'UPDATE_PATRON_COLLECTIONS_EXEMPT',
815             'UPDATE_PATRON_CLAIM_RETURN_COUNT',
816             'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
817             'UPDATE_PATRON_ACTIVE_CARD',
818             'UPDATE_PATRON_PRIMARY_CARD'
819         ];
820
821         var hash = {};
822         angular.forEach(perms_needed, function (p) {
823             hash[p] = true;
824         });
825
826         return $q.when(hash);
827     }
828
829     service.get_surveys = function() {
830         return egLovefield.reconstituteList('asv').then(function(offline) {
831             return egLovefield.reconstituteList('asvq')
832                     .then(function(){
833                         return egLovefield.reconstituteList('asva');
834                     }).then(function() {
835                         angular.forEach(egCore.env.asv.list, function (s) {
836                             s.questions( egCore.env.asva.list.filter( function (a) {
837                                 return q.survey().id == s.id();
838                             }));
839                         });
840
841                         angular.forEach(egCore.env.asvq.list, function (q) {
842                             q.survey( egCore.env.asv.map[ q.survey().id ] );
843                             q.answers( egCore.env.asva.list.filter( function (a) {
844                                 return q.id() == a.question();
845                             }));
846                         });
847
848                         angular.forEach(egCore.env.asva.list, function (a) {
849                             a.question( egCore.env.asvq.map[ a.question().id ] );
850                         });
851
852                         service.surveys = egCore.env.asv.list;
853                         service.survey_questions = egCore.env.asvq.list;
854                         service.survey_answers = egCore.env.asva.list;
855
856                         return $q.when();
857                     });
858         });
859     }
860
861     service.get_stat_cats = function() {
862         return egLovefield.getStatCatsCache().then(
863             function(cats) {
864                 service.stat_cats = cats;
865                 return $q.when();
866             }
867         );
868     };
869
870     service.get_org_settings = function() {
871         return egLovefield.getSettingsCache().then(
872             function (list) {
873                 var hash = {};
874                 angular.forEach(list, function (s) {
875                     hash[s.name] = s.value;
876                 });
877                 service.org_settings = hash;
878                 if (egCore && egCore.env && !egCore.env.aous) {
879                     egCore.env.aous = hash;
880                     console.log('setting egCore.env.aous');
881                 }
882                 return $q.when();
883             }
884         );
885     };
886
887     service.get_ident_types = function() {
888         return egLovefield.reconstituteList('cit').then(function() {
889             service.ident_types = egCore.env.cit.list;
890             return $q.when();
891         });
892     };
893
894     service.get_net_access_levels = function() {
895         return egLovefield.reconstituteList('cnal').then(function() {
896             service.net_access_levels = egCore.env.cnal.list;
897             return $q.when();
898         });
899     }
900
901     service.get_perm_groups = function() {
902         if (egCore.env.pgt) {
903             service.profiles = egCore.env.pgt.list;
904             return service.set_edit_profiles();
905         } else {
906             return egLovefield.reconstituteTree('pgt').then(function(offline) {
907                 service.profiles = egCore.env.pgt.list;
908                 return service.set_edit_profiles();
909             });
910         }
911     }
912
913     service.get_field_doc = function() {
914         return egLovefield.getListFromOfflineCache('fdoc').then(function (list) {
915             angular.forEach(list, function(doc) {
916                 if (!service.field_doc[doc.fm_class()])
917                     service.field_doc[doc.fm_class()] = {};
918                 service.field_doc[doc.fm_class()][doc.field()] = doc;
919             });
920             return $q.when();
921         });
922     };
923
924     service.get_user_settings = function() {
925         var static_types = [
926             'circ.holds_behind_desk', 
927             'circ.collections.exempt', 
928             'opac.hold_notify', 
929             'opac.default_phone', 
930             'opac.default_pickup_location', 
931             'opac.default_sms_carrier', 
932             'opac.default_sms_notify'];
933
934         angular.forEach(static_types, function (t) {
935             service.user_settings[t] = null;
936         });
937
938         return egLovefield.getListFromOfflineCache('cust').then(function (list) {
939             angular.forEach(list, function(stype) {
940                 service.user_setting_types[stype.name()] = stype;
941                 if (static_types.indexOf(stype.name()) == -1) {
942                     service.opt_in_setting_types[stype.name()] = stype;
943                 }
944                 if (stype.reg_default() != undefined) {
945                     service.user_settings[setting.name()] = 
946                         setting.reg_default();
947                 }
948             });
949             return $q.when();
950         });
951     }
952
953     service.invalidate_field = function(patron, field) {
954         return;
955     }
956
957     service.dupe_patron_search = function(patron, type, value) {
958         return $q.when({ search : search, count : 0 });
959     }
960
961     service.init_patron = function(current) {
962
963         if (!current)
964             return service.init_new_patron();
965
966         service.patron = current;
967         return service.init_existing_patron(current)
968     }
969
970     service.ingest_address = function(patron, addr) {
971         addr.valid = addr.valid == 't';
972         addr.within_city_limits = addr.within_city_limits == 't';
973         addr._is_mailing = (patron.mailing_address && 
974             addr.id == patron.mailing_address.id);
975         addr._is_billing = (patron.billing_address && 
976             addr.id == patron.billing_address.id);
977     }
978
979     /*
980      * Existing patron objects reqire some data munging before insertion
981      * into the scope.
982      *
983      * 1. Turn everything into a hash
984      * 2. ... Except certain fields (selectors) whose widgets require objects
985      * 3. Bools must be Boolean, not t/f.
986      */
987     service.init_existing_patron = function(current) {
988
989         service.existing_patron = current;
990
991         var patron = egCore.idl.toHash(current);
992
993         patron.home_ou = egCore.org.get(patron.home_ou.id);
994         patron.expire_date = new Date(Date.parse(patron.expire_date));
995         patron.dob = service.parse_dob(patron.dob);
996         patron.profile = current.profile(); // pre-hash version
997         patron.net_access_level = current.net_access_level();
998         patron.ident_type = current.ident_type();
999         patron.groups = current.groups(); // pre-hash
1000
1001         angular.forEach(
1002             ['juvenile', 'barred', 'active', 'master_account'],
1003             function(field) { patron[field] = patron[field] == 't'; }
1004         );
1005
1006         angular.forEach(patron.cards, function(card) {
1007             card.active = card.active == 't';
1008             if (card.id == patron.card.id) {
1009                 patron.card = card;
1010                 card._primary = 'on';
1011             }
1012         });
1013
1014         angular.forEach(patron.addresses, 
1015             function(addr) { service.ingest_address(patron, addr) });
1016
1017         service.get_linked_addr_users(patron.addresses);
1018
1019         // Remove stat cat entries that link to out-of-scope stat
1020         // cats.  With this, we avoid unnecessarily updating (or worse,
1021         // modifying) stat cat values that are not ours to modify.
1022         patron.stat_cat_entries = patron.stat_cat_entries.filter(
1023             function(map) {
1024                 return Boolean(
1025                     // service.stat_cats only contains in-scope stat cats.
1026                     service.stat_cats.filter(function(cat) { 
1027                         return (cat.id() == map.stat_cat.id) })[0]
1028                 );
1029             }
1030         );
1031
1032         // toss entries for existing stat cat maps into our living 
1033         // stat cat entry map, which is modified within the template.
1034         angular.forEach(patron.stat_cat_entries, function(map) {
1035             service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
1036         });
1037
1038         return patron;
1039     }
1040
1041     service.init_new_patron = function() {
1042         var addr = {
1043             id : service.virt_id--,
1044             isnew : true,
1045             valid : true,
1046             address_type : egCore.strings.REG_ADDR_TYPE,
1047             _is_mailing : true,
1048             _is_billing : true,
1049             within_city_limits : false,
1050             country : service.org_settings['ui.patron.default_country'],
1051         };
1052
1053         var card = {
1054             id : service.virt_id--,
1055             isnew : true,
1056             active : true,
1057             _primary : 'on'
1058         };
1059
1060         var home_ou = egCore.org.get(service.org);
1061
1062         var user = {
1063             isnew : true,
1064             active : true,
1065             card : card,
1066             cards : [card],
1067             home_ou : home_ou,
1068             stat_cat_entries : [],
1069             groups : [],
1070             addresses : [addr]
1071         };
1072
1073         if (service.clone_user)
1074             service.copy_clone_data(user);
1075
1076         if (service.stage_user)
1077             service.copy_stage_data(user);
1078
1079         return user;
1080     }
1081
1082     // dob is always YYYY-MM-DD
1083     // Dates of birth do not contain timezone info, which can lead to
1084     // inconcistent timezone handling, potentially representing
1085     // different points in time, depending on the implementation.
1086     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
1087     // See "Differences in assumed time zone"
1088     // TODO: move this into egDate ?
1089     service.parse_dob = function(dob) {
1090         if (!dob) return null;
1091         var parts = dob.split('-');
1092         var d = new Date(); // always local time zone, yay.
1093         d.setFullYear(parts[0]);
1094         d.setMonth(parts[1] - 1);
1095         d.setDate(parts[2]);
1096         return d;
1097     }
1098
1099     service.copy_stage_data = function(user) {
1100         var cuser = service.stage_user;
1101
1102         // copy the data into our new user object
1103
1104         for (var key in egCore.idl.classes.stgu.field_map) {
1105             if (egCore.idl.classes.au.field_map[key] &&
1106                 !egCore.idl.classes.stgu.field_map[key].virtual) {
1107                 if (cuser.user[key]() !== null)
1108                     user[key] = cuser.user[key]();
1109             }
1110         }
1111
1112         if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
1113         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1114         if (user.ident_type) 
1115             user.ident_type = egCore.env.cit.map[user.ident_type];
1116         user.dob = service.parse_dob(user.dob);
1117
1118         // Clear the usrname if it looks like a UUID
1119         if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/)) 
1120             user.usrname = '';
1121
1122         // Don't use stub address if we have one from the staged user.
1123         if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
1124             user.addresses = [];
1125
1126         // is_mailing=false implies is_billing
1127         function addr_from_stage(stage_addr) {
1128             if (!stage_addr) return;
1129             var cls = stage_addr.classname;
1130
1131             var addr = {
1132                 id : service.virt_id--,
1133                 usr : user.id,
1134                 isnew : true,
1135                 valid : true,
1136                 _is_mailing : cls == 'stgma',
1137                 _is_billing : cls == 'stgba'
1138             };
1139
1140             user.mailing_address = addr;
1141             user.addresses.push(addr);
1142
1143             for (var key in egCore.idl.classes[cls].field_map) {
1144                 if (egCore.idl.classes.aua.field_map[key] &&
1145                     !egCore.idl.classes[cls].field_map[key].virtual) {
1146                     if (stage_addr[key]() !== null)
1147                         addr[key] = stage_addr[key]();
1148                 }
1149             }
1150         }
1151
1152         addr_from_stage(cuser.mailing_addresses[0]);
1153         addr_from_stage(cuser.billing_addresses[0]);
1154
1155         if (user.addresses.length == 1) {
1156             // If there is only one address, 
1157             // use it as both mailing and billing.
1158             var addr = user.addresses[0];
1159             addr._is_mailing = addr._is_billing = true;
1160             user.mailing_address = user.billing_address = addr;
1161         }
1162
1163         if (cuser.cards.length) {
1164             user.card = {
1165                 id : service.virt_id--,
1166                 barcode : cuser.cards[0].barcode(),
1167                 isnew : true,
1168                 active : true,
1169                 _primary : 'on'
1170             };
1171
1172             user.cards.push(user.card);
1173             if (user.usrname == '') 
1174                 user.usrname = card.barcode;
1175         }
1176
1177         angular.forEach(cuser.settings, function(setting) {
1178             service.user_settings[setting.setting()] = Boolean(setting.value());
1179         });
1180     }
1181
1182     // copy select values from the cloned user to the new user.
1183     // user is a hash
1184     service.copy_clone_data = function(user) {
1185         var clone_user = service.clone_user;
1186
1187         // flesh the home org locally
1188         user.home_ou = egCore.org.get(clone_user.home_ou());
1189         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1190
1191         if (!clone_user.billing_address() &&
1192             !clone_user.mailing_address())
1193             return; // no addresses to copy or link
1194
1195         // if the cloned user has any addresses, we don't need 
1196         // the stub address created in init_new_patron.
1197         user.addresses = [];
1198
1199         var copy_addresses = 
1200             service.org_settings['circ.patron_edit.clone.copy_address'];
1201
1202         var clone_fields = [
1203             'day_phone',
1204             'evening_phone',
1205             'other_phone',
1206             'usrgroup'
1207         ]; 
1208
1209         angular.forEach(clone_fields, function(field) {
1210             user[field] = clone_user[field]();
1211         });
1212
1213         if (copy_addresses) {
1214             var bill_addr, mail_addr;
1215
1216             // copy the billing and mailing addresses into new addresses
1217             function clone_addr(addr) {
1218                 var new_addr = egCore.idl.toHash(addr);
1219                 new_addr.id = service.virt_id--;
1220                 new_addr.usr = user.id;
1221                 new_addr.isnew = true;
1222                 new_addr.valid = true;
1223                 user.addresses.push(new_addr);
1224                 return new_addr;
1225             }
1226
1227             if (bill_addr = clone_user.billing_address()) {
1228                 var addr = clone_addr(bill_addr);
1229                 addr._is_billing = true;
1230                 user.billing_address = addr;
1231             }
1232
1233             if (mail_addr = clone_user.mailing_address()) {
1234
1235                 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1236                     user.mailing_address = user.billing_address;
1237                     user.mailing_address._is_mailing = true;
1238                 } else {
1239                     var addr = clone_addr(mail_addr);
1240                     addr._is_mailing = true;
1241                     user.mailing_address = addr;
1242                 }
1243
1244                 if (!bill_addr) {
1245                     // if there is no billing addr, use the mailing addr
1246                     user.billing_address = user.mailing_address;
1247                     user.billing_address._is_billing = true;
1248                 }
1249             }
1250
1251
1252         } else {
1253
1254             // link the billing and mailing addresses
1255             var addr;
1256             if (addr = clone_user.billing_address()) {
1257                 user.billing_address = egCore.idl.toHash(addr);
1258                 user.billing_address._is_billing = true;
1259                 user.addresses.push(user.billing_address);
1260                 user.billing_address._linked_owner_id = clone_user.id();
1261                 user.billing_address._linked_owner = service.format_name(
1262                     clone_user.family_name(),
1263                     clone_user.first_given_name(),
1264                     clone_user.second_given_name()
1265                 );
1266             }
1267
1268             if (addr = clone_user.mailing_address()) {
1269                 if (user.billing_address && 
1270                     addr.id() == user.billing_address.id) {
1271                     // mailing matches billing
1272                     user.mailing_address = user.billing_address;
1273                     user.mailing_address._is_mailing = true;
1274                 } else {
1275                     user.mailing_address = egCore.idl.toHash(addr);
1276                     user.mailing_address._is_mailing = true;
1277                     user.addresses.push(user.mailing_address);
1278                     user.mailing_address._linked_owner_id = clone_user.id();
1279                     user.mailing_address._linked_owner = service.format_name(
1280                         clone_user.family_name(),
1281                         clone_user.first_given_name(),
1282                         clone_user.second_given_name()
1283                     );
1284                 }
1285             }
1286         }
1287     }
1288
1289     // translate the patron back into IDL form
1290     service.save_user = function(phash) {
1291
1292         var patron = egCore.idl.fromHash('au', phash);
1293
1294         patron.home_ou(patron.home_ou().id());
1295         patron.expire_date(patron.expire_date().toISOString());
1296         patron.profile(patron.profile().id());
1297         if (patron.dob()) 
1298             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1299         if (patron.ident_type()) 
1300             patron.ident_type(patron.ident_type().id());
1301         if (patron.net_access_level())
1302             patron.net_access_level(patron.net_access_level().id());
1303
1304         angular.forEach(
1305             ['juvenile', 'barred', 'active', 'master_account'],
1306             function(field) { patron[field](phash[field] ? 't' : 'f'); }
1307         );
1308
1309         var card_hashes = patron.cards();
1310         patron.cards([]);
1311         angular.forEach(card_hashes, function(chash) {
1312             var card = egCore.idl.fromHash('ac', chash)
1313             card.usr(patron.id());
1314             card.active(chash.active ? 't' : 'f');
1315             patron.cards().push(card);
1316             if (chash._primary) {
1317                 patron.card(card);
1318             }
1319         });
1320
1321         var addr_hashes = patron.addresses();
1322         patron.addresses([]);
1323         angular.forEach(addr_hashes, function(addr_hash) {
1324             if (!addr_hash.isnew && !addr_hash.isdeleted) 
1325                 addr_hash.ischanged = true;
1326             var addr = egCore.idl.fromHash('aua', addr_hash);
1327             patron.addresses().push(addr);
1328             addr.valid(addr.valid() ? 't' : 'f');
1329             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1330             if (addr_hash._is_mailing) patron.mailing_address(addr);
1331             if (addr_hash._is_billing) patron.billing_address(addr);
1332         });
1333
1334         patron.survey_responses([]);
1335         angular.forEach(service.survey_responses, function(answer) {
1336             var question = service.survey_questions[answer.question()];
1337             var resp = new egCore.idl.asvr();
1338             resp.isnew(true);
1339             resp.survey(question.survey());
1340             resp.question(question.id());
1341             resp.answer(answer.id());
1342             resp.usr(patron.id());
1343             resp.answer_date('now');
1344             patron.survey_responses().push(resp);
1345         });
1346         
1347         // re-object-ify the patron stat cat entry maps
1348         var maps = [];
1349         angular.forEach(patron.stat_cat_entries(), function(entry) {
1350             var e = egCore.idl.fromHash('actscecm', entry);
1351             e.stat_cat(e.stat_cat().id);
1352             maps.push(e);
1353         });
1354         patron.stat_cat_entries(maps);
1355
1356         // service.stat_cat_entry_maps maps stats to values
1357         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1358         angular.forEach(
1359             service.stat_cat_entry_maps, function(value, cat_id) {
1360
1361             // see if we already have a mapping for this entry
1362             var existing = patron.stat_cat_entries().filter(
1363                 function(e) { return e.stat_cat() == cat_id })[0];
1364
1365             if (existing) { // we have a mapping
1366                 // if the existing mapping matches the new one,
1367                 // there' nothing left to do
1368                 if (existing.stat_cat_entry() == value) return;
1369
1370                 // mappings differ.  delete the old one and create
1371                 // a new one below.
1372                 existing.isdeleted(true);
1373             }
1374
1375             var newmap = new egCore.idl.actscecm();
1376             newmap.target_usr(patron.id());
1377             newmap.isnew(true);
1378             newmap.stat_cat(cat_id);
1379             newmap.stat_cat_entry(value);
1380             patron.stat_cat_entries().push(newmap);
1381         });
1382
1383         if (!patron.isnew()) patron.ischanged(true);
1384
1385         return egLovefield.addOfflineXact({
1386             user        : egCore.idl.toHash(patron),
1387             timestamp   : parseInt(new Date().getTime() / 1000),
1388             type        : 'register',
1389             delta       : 0
1390         }).then(function (success) {
1391             if (success) return patron;
1392         });
1393     }
1394
1395     service.remove_staged_user = function() {
1396         if (!service.stage_user) return $q.when();
1397         return egCore.net.request(
1398             'open-ils.actor',
1399             'open-ils.actor.user.stage.delete',
1400             egCore.auth.token(),
1401             service.stage_user.user.row_id()
1402         );
1403     }
1404
1405     service.save_user_settings = function(new_user, user_settings) {
1406         return;
1407     }
1408
1409     // Applies field-specific validation regex's from org settings 
1410     // to form fields.  Be careful not remove any pattern data we
1411     // are not explicitly over-writing in the provided patterns obj.
1412     service.set_field_patterns = function(patterns) {
1413         if (service.org_settings['opac.username_regex']) {
1414             patterns.au.usrname = 
1415                 new RegExp(service.org_settings['opac.username_regex']);
1416         }
1417
1418         if (service.org_settings['opac.barcode_regex']) {
1419             patterns.ac.barcode = 
1420                 new RegExp(service.org_settings['opac.barcode_regex']);
1421         }
1422
1423         if (service.org_settings['global.password_regex']) {
1424             patterns.au.passwd = 
1425                 new RegExp(service.org_settings['global.password_regex']);
1426         }
1427
1428         var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1429         if (phone_reg) {
1430             // apply generic phone regex first, replace below as needed.
1431             patterns.au.day_phone = new RegExp(phone_reg);
1432             patterns.au.evening_phone = new RegExp(phone_reg);
1433             patterns.au.other_phone = new RegExp(phone_reg);
1434         }
1435
1436         // the remaining patterns fit a well-known key name pattern
1437
1438         angular.forEach(service.org_settings, function(val, key) {
1439             if (!val) return;
1440             var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1441             if (!parts) return;
1442             var cls = parts[1];
1443             var name = parts[2];
1444             patterns[cls][name] = new RegExp(val);
1445         });
1446     }
1447
1448     return service;
1449 }])
1450
1451 .controller('PatronRegCtrl',
1452        ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1453         'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1454         'egWorkLog','$timeout','egLovefield','$rootScope',
1455 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1456          patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1457          egWorkLog , $timeout , egLovefield , $rootScope) {
1458
1459     $scope.rs = $rootScope;
1460     if ($scope.workstation_obj) patronRegSvc.org = $scope.workstation_obj.owning_lib;
1461     $scope.offline = true;
1462
1463     $scope.page_data_loaded = false;
1464     $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1465     $scope.stage_username = 
1466         patronRegSvc.stage_username = $routeParams.stage_username;
1467     $scope.patron_id = 
1468         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1469
1470     // for existing patrons, disable barcode input by default
1471     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1472     $scope.focus_bc = !Boolean($scope.patron_id);
1473     $scope.address_alerts = [];
1474     $scope.dupe_counts = {};
1475
1476     // map of perm name to true/false for perms the logged in user
1477     // has at the currently selected patron home org unit.
1478     $scope.perms = {};
1479
1480     $scope.edit_passthru = {};
1481
1482     // 0=all, 1=suggested, 2=all
1483     $scope.edit_passthru.vis_level = 2; 
1484
1485     // Apply default values for new patrons during initial registration
1486     // prs is shorthand for patronSvc
1487     function set_new_patron_defaults(prs) {
1488         if (!$scope.patron.passwd) {
1489             // passsword may originate from staged user.
1490             $scope.generate_password();
1491         }
1492         $scope.hold_notify_phone = true;
1493         $scope.hold_notify_email = true;
1494
1495         // staged users may be loaded w/ a profile.
1496         $scope.set_expire_date();
1497
1498         if (prs.org_settings['ui.patron.default_ident_type']) {
1499             // $scope.patron needs this field to be an object
1500             var id = prs.org_settings['ui.patron.default_ident_type'];
1501             var ident_type = $scope.ident_types.filter(
1502                 function(type) { return type.id() == id })[0];
1503             $scope.patron.ident_type = ident_type;
1504         }
1505         if (prs.org_settings['ui.patron.default_inet_access_level']) {
1506             // $scope.patron needs this field to be an object
1507             var id = prs.org_settings['ui.patron.default_inet_access_level'];
1508             var level = $scope.net_access_levels.filter(
1509                 function(lvl) { return lvl.id() == id })[0];
1510             $scope.patron.net_access_level = level;
1511         }
1512         if (prs.org_settings['ui.patron.default_country']) {
1513             $scope.patron.addresses[0].country = 
1514                 prs.org_settings['ui.patron.default_country'];
1515         }
1516     }
1517
1518     // A null or undefined pattern leads to exceptions.  Before the
1519     // patterns are loaded from the server, default all patterns
1520     // to an innocuous regex.  To avoid re-creating numerous
1521     // RegExp objects, cache the stub RegExp after initial creation.
1522     // note: angular docs say ng-pattern accepts a regexp or string,
1523     // but as of writing, it only works with a regexp object.
1524     // (Likely an angular 1.2 vs. 1.4 issue).
1525     var field_patterns = {au : {}, ac : {}, aua : {}};
1526     $scope.field_pattern = function(cls, field) { 
1527         if (!field_patterns[cls][field])
1528             field_patterns[cls][field] = new RegExp('.*');
1529         return field_patterns[cls][field];
1530     }
1531
1532     patronRegSvc.offlineMode($scope.offline); // force offline if ng-init'd to do so
1533     patronRegSvc.init().then(function() {
1534         // called after initTab and patronRegSvc.init have completed
1535     
1536         var prs = patronRegSvc; // brevity
1537         // in standalone mode, we have no patronSvc
1538         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1539         $scope.field_doc = prs.field_doc;
1540         $scope.edit_profiles = prs.edit_profiles;
1541         $scope.ident_types = prs.ident_types;
1542         $scope.net_access_levels = prs.net_access_levels;
1543         $scope.user_setting_types = prs.user_setting_types;
1544         $scope.opt_in_setting_types = prs.opt_in_setting_types;
1545         $scope.org_settings = prs.org_settings;
1546         $scope.sms_carriers = prs.sms_carriers;
1547         $scope.stat_cats = prs.stat_cats;
1548         $scope.surveys = prs.surveys;
1549         $scope.survey_responses = prs.survey_responses;
1550         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1551         $scope.stage_user = prs.stage_user;
1552         $scope.stage_user_requestor = prs.stage_user_requestor;
1553     
1554         $scope.user_settings = prs.user_settings;
1555         // clone the user settings back into the patronRegSvc so
1556         // we have a copy of the original state of the settings.
1557         prs.user_settings = {};
1558         angular.forEach($scope.user_settings, function(val, key) {
1559             prs.user_settings[key] = val;
1560         });
1561     
1562         extract_hold_notify();
1563         $scope.handle_home_org_changed();
1564     
1565         if ($scope.org_settings['ui.patron.edit.default_suggested'])
1566             $scope.edit_passthru.vis_level = 1;
1567     
1568         if ($scope.patron.isnew) 
1569             set_new_patron_defaults(prs);
1570     
1571         $scope.page_data_loaded = true;
1572     
1573         prs.set_field_patterns(field_patterns);
1574         apply_username_regex();
1575     });
1576
1577     // update the currently displayed field documentation
1578     $scope.set_selected_field_doc = function(cls, field) {
1579         $scope.selected_field_doc = $scope.field_doc[cls][field];
1580     }
1581
1582     // returns the tree depth of the selected profile group tree node.
1583     $scope.pgt_depth = function(grp) {
1584         var d = 0;
1585         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1586         return d;
1587     }
1588
1589     // IDL fields used for labels in the UI.
1590     $scope.idl_fields = {
1591         au  : egCore.idl.classes.au.field_map,
1592         ac  : egCore.idl.classes.ac.field_map,
1593         aua : egCore.idl.classes.aua.field_map
1594     };
1595
1596     // field visibility cache.  Some fields are universally required.
1597     // 3 == value universally required
1598     // 2 == field is visible by default
1599     // 1 == field is suggested by default
1600     var field_visibility = {};
1601     var default_field_visibility = {
1602         'ac.barcode' : 3,
1603         'au.usrname' : 3,
1604         'au.passwd' :  3,
1605         'au.first_given_name' : 3,
1606         'au.family_name' : 3,
1607         'au.ident_type' : 3,
1608         'au.home_ou' : 3,
1609         'au.profile' : 3,
1610         'au.expire_date' : 3,
1611         'au.net_access_level' : 3,
1612         'aua.address_type' : 3,
1613         'aua.post_code' : 3,
1614         'aua.street1' : 3,
1615         'aua.street2' : 2,
1616         'aua.city' : 3,
1617         'aua.county' : 2,
1618         'aua.state' : 2,
1619         'aua.country' : 3,
1620         'aua.valid' : 2,
1621         'aua.within_city_limits' : 2,
1622         'stat_cats' : 1,
1623         'surveys' : 1
1624     }; 
1625
1626     // Returns true if the selected field should be visible
1627     // given the current required/suggested/all setting.
1628     // The visibility flag applied to each field as a result of calling
1629     // this function also sets (via the same flag) the requiredness state.
1630     $scope.show_field = function(field_key) {
1631         // org settings have not been received yet.
1632         if (!$scope.org_settings) return false;
1633
1634         if (field_visibility[field_key] == undefined) {
1635             // compile and cache the visibility for the selected field
1636
1637             var req_set = 'ui.patron.edit.' + field_key + '.require';
1638             var sho_set = 'ui.patron.edit.' + field_key + '.show';
1639             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1640
1641             if ($scope.org_settings[req_set]) {
1642                 field_visibility[field_key] = 3;
1643
1644             } else if ($scope.org_settings[sho_set]) {
1645                 field_visibility[field_key] = 2;
1646
1647             } else if ($scope.org_settings[sug_set]) {
1648                 field_visibility[field_key] = 1;
1649             }
1650         }
1651
1652         if (field_visibility[field_key] == undefined) {
1653             // No org settings were applied above.  Use the default
1654             // settings if present or assume the field has no
1655             // visibility flags applied.
1656             field_visibility[field_key] = 
1657                 default_field_visibility[field_key] || 0;
1658         }
1659
1660         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1661     }
1662
1663     // See $scope.show_field().
1664     // A field with visbility level 3 means it's required.
1665     $scope.field_required = function(cls, field) {
1666
1667         // Value in the password field is not required
1668         // for existing patrons.
1669         if (field == 'passwd' && $scope.patron && !$scope.patron.isnew) 
1670           return false;
1671
1672         return (field_visibility[cls + '.' + field] == 3 || default_field_visibility[cls + '.' + field] == 3);
1673     }
1674
1675     // generates a random 4-digit password
1676     $scope.generate_password = function() {
1677         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1678     }
1679
1680     $scope.set_expire_date = function() {
1681         if (!$scope.patron.profile) return;
1682         var seconds = egCore.date.intervalToSeconds(
1683             $scope.patron.profile.perm_interval());
1684         var now_epoch = new Date().getTime();
1685         $scope.patron.expire_date = new Date(
1686             now_epoch + (seconds * 1000 /* milliseconds */))
1687     }
1688
1689     // grp is the pgt object
1690     $scope.set_profile = function(grp) {
1691         $scope.patron.profile = grp;
1692         $scope.set_expire_date();
1693         $scope.field_modified();
1694     }
1695
1696     $scope.invalid_profile = function() {
1697         return !(
1698             $scope.patron && 
1699             $scope.patron.profile && 
1700             $scope.patron.profile.usergroup() == 't'
1701         );
1702     }
1703
1704     $scope.new_address = function() {
1705         var addr = egCore.idl.toHash(new egCore.idl.aua());
1706         patronRegSvc.ingest_address($scope.patron, addr);
1707         addr.id = patronRegSvc.virt_id--;
1708         addr.isnew = true;
1709         addr.valid = true;
1710         addr.within_city_limits = true;
1711         addr.country = $scope.org_settings['ui.patron.default_country'];
1712         $scope.patron.addresses.push(addr);
1713     }
1714
1715     // keep deleted addresses out of the patron object so
1716     // they won't appear in the UI.  They'll be re-inserted
1717     // when the patron is updated.
1718     deleted_addresses = [];
1719     $scope.delete_address = function(id) {
1720
1721         if ($scope.patron.isnew &&
1722             $scope.patron.addresses.length == 1 &&
1723             $scope.org_settings['ui.patron.registration.require_address']) {
1724             egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1725             return;
1726         }
1727
1728         var addresses = [];
1729         angular.forEach($scope.patron.addresses, function(addr) {
1730             if (addr.id == id) {
1731                 if (id > 0) {
1732                     addr.isdeleted = true;
1733                     deleted_addresses.push(addr);
1734                 }
1735             } else {
1736                 addresses.push(addr);
1737             }
1738         });
1739         $scope.patron.addresses = addresses;
1740     } 
1741
1742     $scope.post_code_changed = function(addr) { 
1743         if ($scope.offline) return;
1744         egCore.net.request(
1745             'open-ils.search', 'open-ils.search.zip', addr.post_code)
1746         .then(function(resp) {
1747             if (!resp) return;
1748             if (resp.city) addr.city = resp.city;
1749             if (resp.state) addr.state = resp.state;
1750             if (resp.county) addr.county = resp.county;
1751             if (resp.alert) alert(resp.alert);
1752         });
1753     }
1754
1755     $scope.replace_card = function() {
1756         $scope.patron.card.active = false;
1757         $scope.patron.card.ischanged = true;
1758         $scope.disable_bc = false;
1759
1760         var new_card = egCore.idl.toHash(new egCore.idl.ac());
1761         new_card.id = patronRegSvc.virt_id--;
1762         new_card.isnew = true;
1763         new_card.active = true;
1764         new_card._primary = 'on';
1765         $scope.patron.card = new_card;
1766         $scope.patron.cards.push(new_card);
1767     }
1768
1769     $scope.day_phone_changed = function(phone) {
1770         if (phone && $scope.patron.isnew && 
1771             $scope.org_settings['patron.password.use_phone']) {
1772             $scope.patron.passwd = phone.substr(-4);
1773         }
1774     }
1775
1776     $scope.barcode_changed = function(bc) {
1777         if (!bc) return;
1778         if (!$scope.patron.usrname)
1779             $scope.patron.usrname = bc;
1780     }
1781
1782     $scope.cards_dialog = function() {
1783         $uibModal.open({
1784             templateUrl: './circ/patron/t_patron_cards_dialog',
1785             controller: 
1786                    ['$scope','$uibModalInstance','cards','perms',
1787             function($scope , $uibModalInstance , cards , perms) {
1788                 // scope here is the modal-level scope
1789                 $scope.args = {cards : cards};
1790                 $scope.perms = perms;
1791                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1792                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1793             }],
1794             resolve : {
1795                 cards : function() {
1796                     // scope here is the controller-level scope
1797                     return $scope.patron.cards;
1798                 },
1799                 perms : function() {
1800                     return $scope.perms;
1801                 }
1802             }
1803         }).result.then(
1804             function(args) {
1805                 angular.forEach(args.cards, function(card) {
1806                     card.ischanged = true; // assume cards need updating, OK?
1807                     if (card._primary == 'on' && 
1808                         card.id != $scope.patron.card.id) {
1809                         $scope.patron.card = card;
1810                     }
1811                 });
1812             }
1813         );
1814     }
1815
1816     $scope.set_addr_type = function(addr, type) {
1817         var addrs = $scope.patron.addresses;
1818         if (addr['_is_'+type]) {
1819             angular.forEach(addrs, function(a) {
1820                 if (a.id != addr.id) a['_is_'+type] = false;
1821             });
1822         } else {
1823             // unchecking mailing/billing means we have to randomly
1824             // select another address to fill that role.  Select the
1825             // first address in the list (that does not match the
1826             // modifed address)
1827             for (var i = 0; i < addrs.length; i++) {
1828                 if (addrs[i].id != addr.id) {
1829                     addrs[i]['_is_' + type] = true;
1830                     break;
1831                 }
1832             }
1833         }
1834     }
1835
1836
1837     // Translate hold notify preferences from the form/scope back into a 
1838     // single user setting value for opac.hold_notify.
1839     function compress_hold_notify() {
1840         var hold_notify = '';
1841         var splitter = '';
1842         if ($scope.hold_notify_phone) {
1843             hold_notify = 'phone';
1844             splitter = ':';
1845         }
1846         if ($scope.hold_notify_email) {
1847             hold_notify = splitter + 'email';
1848             splitter = ':';
1849         }
1850         if ($scope.hold_notify_sms) {
1851             hold_notify = splitter + 'sms';
1852             splitter = ':';
1853         }
1854         $scope.user_settings['opac.hold_notify'] = hold_notify;
1855     }
1856
1857     // dialog for selecting additional permission groups
1858     $scope.secondary_groups_dialog = function() {
1859         $uibModal.open({
1860             templateUrl: './circ/patron/t_patron_groups_dialog',
1861             controller: 
1862                    ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1863             function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1864
1865                 $scope.pgt_depth = pgt_depth;
1866                 $scope.args = {
1867                     linked_groups : linked_groups,
1868                     edit_profiles : patronRegSvc.edit_profiles,
1869                     new_profile   : patronRegSvc.edit_profiles[0]
1870                 };
1871
1872                 // add a new group to the linked groups list
1873                 $scope.link_group = function($event, grp) {
1874                     var found = false; // avoid duplicates
1875                     angular.forEach($scope.args.linked_groups, 
1876                         function(g) {if (g.id() == grp.id()) found = true});
1877                     if (!found) $scope.args.linked_groups.push(grp);
1878                     $event.preventDefault(); // avoid close
1879                 }
1880
1881                 // remove a group from the linked groups list
1882                 $scope.unlink_group = function($event, grp) {
1883                     $scope.args.linked_groups = 
1884                         $scope.args.linked_groups.filter(function(g) {
1885                         return g.id() != grp.id()
1886                     });
1887                     $event.preventDefault(); // avoid close
1888                 }
1889
1890                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1891                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1892             }],
1893             resolve : {
1894                 linked_groups : function() { return $scope.patron.groups },
1895                 pgt_depth : function() { return $scope.pgt_depth }
1896             }
1897         }).result.then(
1898             function(args) {
1899
1900                 if ($scope.patron.isnew) {
1901                     // groups must be linked for new patrons after the
1902                     // patron is created.
1903                     $scope.patron.groups = args.linked_groups;
1904                     return;
1905                 }
1906
1907                 // update links groups for existing users in real time.
1908                 var ids = args.linked_groups.map(function(g) {return g.id()});
1909                 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1910                 .then(function(success) {
1911                     if (success)
1912                         $scope.patron.groups = args.linked_groups;
1913                 });
1914             }
1915         );
1916     }
1917
1918     function extract_hold_notify() {
1919         notify = $scope.user_settings['opac.hold_notify'];
1920         if (!notify) return;
1921         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1922         $scope.hold_notify_email = Boolean(notify.match(/email/));
1923         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1924     }
1925
1926     $scope.invalidate_field = function(field) {
1927         patronRegSvc.invalidate_field($scope.patron, field);
1928     }
1929
1930     address_alert = function(addr) {
1931         if ($scope.offline) return;
1932         var args = {
1933             street1: addr.street1,
1934             street2: addr.street2,
1935             city: addr.city,
1936             state: addr.state,
1937             county: addr.county,
1938             country: addr.country,
1939             post_code: addr.post_code,
1940             mailing_address: addr._is_mailing,
1941             billing_address: addr._is_billing
1942         }
1943
1944         egCore.net.request(
1945             'open-ils.actor',
1946             'open-ils.actor.address_alert.test',
1947             egCore.auth.token(), egCore.auth.user().ws_ou(), args
1948             ).then(function(res) {
1949                 $scope.address_alerts = res;
1950         });
1951     }
1952
1953     $scope.dupe_value_changed = function(type, value) {
1954         $scope.dupe_counts[type] = 0;
1955         patronRegSvc.dupe_patron_search($scope.patron, type, value)
1956         .then(function(res) {
1957             $scope.dupe_counts[type] = res.count;
1958             if (res.count) {
1959                 $scope.dupe_search_encoded = 
1960                     encodeURIComponent(js2JSON(res.search));
1961             } else {
1962                 $scope.dupe_search_encoded = '';
1963             }
1964         });
1965     }
1966
1967     // Dummy function in offline mode
1968     $scope.handle_home_org_changed = function() {}
1969
1970     // This is called with every character typed in a form field,
1971     // since that's the only way to gaurantee something has changed.
1972     // See handle_field_changed for ng-change vs. ng-blur.
1973     $scope.field_modified = function() {
1974         // Call attach with every field change, regardless of whether
1975         // it's been called before.  This will allow for re-attach after
1976         // the user clicks through the unload warning. egUnloadPrompt
1977         // will ensure we only attach once.
1978         egUnloadPrompt.attach($rootScope);
1979     }
1980
1981     // also monitor when form is changed *by the user*, as using
1982     // an ng-change handler doesn't work with eg-date-input
1983     $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1984         if (!newVal) egUnloadPrompt.attach($rootScope);
1985     });
1986
1987     // username regex (if present) must be removed any time
1988     // the username matches the barcode to avoid firing the
1989     // invalid field handlers.
1990     function apply_username_regex() {
1991         var regex = $scope.org_settings['opac.username_regex'];
1992         if (regex) {
1993             if ($scope.patron.card.barcode) {
1994                 // username must match the regex or the barcode
1995                 field_patterns.au.usrname = 
1996                     new RegExp(
1997                         regex + '|^' + $scope.patron.card.barcode + '$');
1998             } else {
1999                 // username must match the regex
2000                 field_patterns.au.usrname = new RegExp(regex);
2001             }
2002         } else {
2003             // username can be any format.
2004             field_patterns.au.usrname = new RegExp('.*');
2005         }
2006     }
2007
2008     // obj could be the patron, an address, etc.
2009     // This is called any time a form field achieves then loses focus.
2010     // It does not necessarily mean the field has changed.
2011     // The alternative is ng-change, but it's called with each character
2012     // typed, which would be overkill for many of the actions called here.
2013     $scope.handle_field_changed = function(obj, field_name) {
2014         if (!obj) return;
2015
2016         var cls = obj.classname; // set by egIdl
2017         var value = obj[field_name];
2018
2019         // Hush!
2020         //console.log('changing field ' + field_name + ' to ' + value);
2021
2022         switch (field_name) {
2023             case 'day_phone' : 
2024                 if ($scope.patron.day_phone && 
2025                     $scope.patron.isnew && 
2026                     $scope.org_settings['patron.password.use_phone']) {
2027                     $scope.patron.passwd = phone.substr(-4);
2028                 }
2029                 break;
2030
2031             case 'barcode':
2032                 apply_username_regex();
2033                 $scope.barcode_changed(value);
2034                 break;
2035
2036             case 'dob':
2037                 maintain_juvenile_flag();
2038                 break;
2039
2040             default:
2041                 break;
2042         }
2043     }
2044
2045     // patron.juvenile is set to true if the user was born after
2046     function maintain_juvenile_flag() {
2047         if ( !($scope.patron && $scope.patron.dob) ) return;
2048
2049         var juv_interval = 
2050             $scope.org_settings['global.juvenile_age_threshold'] 
2051             || '18 years';
2052
2053         var base = new Date();
2054
2055         base.setTime(base.getTime() - 
2056             Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2057
2058         $scope.patron.juvenile = ($scope.patron.dob > base);
2059     }
2060
2061     // returns true (disable) for orgs that cannot have users.
2062     $scope.disable_home_org = function(org_id) {
2063         if (!org_id) return;
2064         var org = egCore.org.get(org_id);
2065         return (
2066             org &&
2067             org.ou_type() &&
2068             org.ou_type().can_have_users() == 'f'
2069         );
2070     }
2071
2072     // Returns true if the Save and Save & Clone buttons should be disabled.
2073     $scope.edit_passthru.hide_save_actions = function() {
2074         return false;
2075     }
2076
2077     // Returns true if any input elements are tagged as invalid
2078     // via Angular patterns or required attributes.
2079     function form_has_invalid_fields() {
2080         return $('#patron-reg-container .ng-invalid').length > 0;
2081     }
2082
2083     function form_is_incomplete() {
2084         return (
2085             $scope.dupe_username ||
2086             $scope.dupe_barcode ||
2087             form_has_invalid_fields()
2088         );
2089
2090     }
2091
2092     $scope.edit_passthru.save = function(save_args) {
2093         if (!save_args) save_args = {};
2094
2095         if (form_is_incomplete()) {
2096             // User has not provided valid values for all required fields.
2097             return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2098         }
2099
2100         // remove page unload warning prompt
2101         egUnloadPrompt.clear();
2102
2103         // toss the deleted addresses back into the patron's list of
2104         // addresses so it's included in the update
2105         $scope.patron.addresses = 
2106             $scope.patron.addresses.concat(deleted_addresses);
2107         
2108         compress_hold_notify();
2109
2110         var updated_user;
2111
2112         patronRegSvc.save_user($scope.patron)
2113         .then($scope.rs.save_offline_xacts)
2114         .then(function(new_user) { 
2115             // reload the current page
2116             $window.location.href = location.href;
2117         });
2118     }
2119 }])