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