12cfc3fe87c9f7dcb477f17f1d4b9ddc8dfda11f
[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         $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                 if (!service.field_doc[doc.fm_class()])
909                     service.field_doc[doc.fm_class()] = {};
910                 service.field_doc[doc.fm_class()][doc.field()] = doc;
911             });
912             return $q.when();
913         });
914     };
915
916     service.get_user_settings = function() {
917         var static_types = [
918             'circ.holds_behind_desk', 
919             'circ.collections.exempt', 
920             'opac.hold_notify', 
921             'opac.default_phone', 
922             'opac.default_pickup_location', 
923             'opac.default_sms_carrier', 
924             'opac.default_sms_notify'];
925
926         angular.forEach(static_types, function (t) {
927             service.user_settings[t] = null;
928         });
929
930         return egLovefield.getListFromOfflineCache('cust').then(function (list) {
931             angular.forEach(list, function(stype) {
932                 service.user_setting_types[stype.name()] = stype;
933                 if (static_types.indexOf(stype.name()) == -1) {
934                     service.opt_in_setting_types[stype.name()] = stype;
935                 }
936                 if (stype.reg_default() != undefined) {
937                     service.user_settings[setting.name()] = 
938                         setting.reg_default();
939                 }
940             });
941             return $q.when();
942         });
943     }
944
945     service.invalidate_field = function(patron, field) {
946         return;
947     }
948
949     service.dupe_patron_search = function(patron, type, value) {
950         return $q.when({ search : search, count : 0 });
951     }
952
953     service.init_patron = function(current) {
954
955         if (!current)
956             return service.init_new_patron();
957
958         service.patron = current;
959         return service.init_existing_patron(current)
960     }
961
962     service.ingest_address = function(patron, addr) {
963         addr.valid = addr.valid == 't';
964         addr.within_city_limits = addr.within_city_limits == 't';
965         addr._is_mailing = (patron.mailing_address && 
966             addr.id == patron.mailing_address.id);
967         addr._is_billing = (patron.billing_address && 
968             addr.id == patron.billing_address.id);
969     }
970
971     /*
972      * Existing patron objects reqire some data munging before insertion
973      * into the scope.
974      *
975      * 1. Turn everything into a hash
976      * 2. ... Except certain fields (selectors) whose widgets require objects
977      * 3. Bools must be Boolean, not t/f.
978      */
979     service.init_existing_patron = function(current) {
980
981         service.existing_patron = current;
982
983         var patron = egCore.idl.toHash(current);
984
985         patron.home_ou = egCore.org.get(patron.home_ou.id);
986         patron.expire_date = new Date(Date.parse(patron.expire_date));
987         patron.dob = service.parse_dob(patron.dob);
988         patron.profile = current.profile(); // pre-hash version
989         patron.net_access_level = current.net_access_level();
990         patron.ident_type = current.ident_type();
991         patron.groups = current.groups(); // pre-hash
992
993         angular.forEach(
994             ['juvenile', 'barred', 'active', 'master_account'],
995             function(field) { patron[field] = patron[field] == 't'; }
996         );
997
998         angular.forEach(patron.cards, function(card) {
999             card.active = card.active == 't';
1000             if (card.id == patron.card.id) {
1001                 patron.card = card;
1002                 card._primary = 'on';
1003             }
1004         });
1005
1006         angular.forEach(patron.addresses, 
1007             function(addr) { service.ingest_address(patron, addr) });
1008
1009         service.get_linked_addr_users(patron.addresses);
1010
1011         // Remove stat cat entries that link to out-of-scope stat
1012         // cats.  With this, we avoid unnecessarily updating (or worse,
1013         // modifying) stat cat values that are not ours to modify.
1014         patron.stat_cat_entries = patron.stat_cat_entries.filter(
1015             function(map) {
1016                 return Boolean(
1017                     // service.stat_cats only contains in-scope stat cats.
1018                     service.stat_cats.filter(function(cat) { 
1019                         return (cat.id() == map.stat_cat.id) })[0]
1020                 );
1021             }
1022         );
1023
1024         // toss entries for existing stat cat maps into our living 
1025         // stat cat entry map, which is modified within the template.
1026         angular.forEach(patron.stat_cat_entries, function(map) {
1027             service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
1028         });
1029
1030         return patron;
1031     }
1032
1033     service.init_new_patron = function() {
1034         var addr = {
1035             id : service.virt_id--,
1036             isnew : true,
1037             valid : true,
1038             address_type : egCore.strings.REG_ADDR_TYPE,
1039             _is_mailing : true,
1040             _is_billing : true,
1041             within_city_limits : false,
1042             country : service.org_settings['ui.patron.default_country'],
1043         };
1044
1045         var card = {
1046             id : service.virt_id--,
1047             isnew : true,
1048             active : true,
1049             _primary : 'on'
1050         };
1051
1052         var home_ou = egCore.org.get(service.org);
1053
1054         var user = {
1055             isnew : true,
1056             active : true,
1057             card : card,
1058             cards : [card],
1059             home_ou : home_ou,
1060             stat_cat_entries : [],
1061             groups : [],
1062             addresses : [addr]
1063         };
1064
1065         if (service.clone_user)
1066             service.copy_clone_data(user);
1067
1068         if (service.stage_user)
1069             service.copy_stage_data(user);
1070
1071         return user;
1072     }
1073
1074     // dob is always YYYY-MM-DD
1075     // Dates of birth do not contain timezone info, which can lead to
1076     // inconcistent timezone handling, potentially representing
1077     // different points in time, depending on the implementation.
1078     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
1079     // See "Differences in assumed time zone"
1080     // TODO: move this into egDate ?
1081     service.parse_dob = function(dob) {
1082         if (!dob) return null;
1083         var parts = dob.split('-');
1084         var d = new Date(); // always local time zone, yay.
1085         d.setFullYear(parts[0]);
1086         d.setMonth(parts[1] - 1);
1087         d.setDate(parts[2]);
1088         return d;
1089     }
1090
1091     service.copy_stage_data = function(user) {
1092         var cuser = service.stage_user;
1093
1094         // copy the data into our new user object
1095
1096         for (var key in egCore.idl.classes.stgu.field_map) {
1097             if (egCore.idl.classes.au.field_map[key] &&
1098                 !egCore.idl.classes.stgu.field_map[key].virtual) {
1099                 if (cuser.user[key]() !== null)
1100                     user[key] = cuser.user[key]();
1101             }
1102         }
1103
1104         if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
1105         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1106         if (user.ident_type) 
1107             user.ident_type = egCore.env.cit.map[user.ident_type];
1108         user.dob = service.parse_dob(user.dob);
1109
1110         // Clear the usrname if it looks like a UUID
1111         if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/)) 
1112             user.usrname = '';
1113
1114         // Don't use stub address if we have one from the staged user.
1115         if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
1116             user.addresses = [];
1117
1118         // is_mailing=false implies is_billing
1119         function addr_from_stage(stage_addr) {
1120             if (!stage_addr) return;
1121             var cls = stage_addr.classname;
1122
1123             var addr = {
1124                 id : service.virt_id--,
1125                 usr : user.id,
1126                 isnew : true,
1127                 valid : true,
1128                 _is_mailing : cls == 'stgma',
1129                 _is_billing : cls == 'stgba'
1130             };
1131
1132             user.mailing_address = addr;
1133             user.addresses.push(addr);
1134
1135             for (var key in egCore.idl.classes[cls].field_map) {
1136                 if (egCore.idl.classes.aua.field_map[key] &&
1137                     !egCore.idl.classes[cls].field_map[key].virtual) {
1138                     if (stage_addr[key]() !== null)
1139                         addr[key] = stage_addr[key]();
1140                 }
1141             }
1142         }
1143
1144         addr_from_stage(cuser.mailing_addresses[0]);
1145         addr_from_stage(cuser.billing_addresses[0]);
1146
1147         if (user.addresses.length == 1) {
1148             // If there is only one address, 
1149             // use it as both mailing and billing.
1150             var addr = user.addresses[0];
1151             addr._is_mailing = addr._is_billing = true;
1152             user.mailing_address = user.billing_address = addr;
1153         }
1154
1155         if (cuser.cards.length) {
1156             user.card = {
1157                 id : service.virt_id--,
1158                 barcode : cuser.cards[0].barcode(),
1159                 isnew : true,
1160                 active : true,
1161                 _primary : 'on'
1162             };
1163
1164             user.cards.push(user.card);
1165             if (user.usrname == '') 
1166                 user.usrname = card.barcode;
1167         }
1168
1169         angular.forEach(cuser.settings, function(setting) {
1170             service.user_settings[setting.setting()] = Boolean(setting.value());
1171         });
1172     }
1173
1174     // copy select values from the cloned user to the new user.
1175     // user is a hash
1176     service.copy_clone_data = function(user) {
1177         var clone_user = service.clone_user;
1178
1179         // flesh the home org locally
1180         user.home_ou = egCore.org.get(clone_user.home_ou());
1181         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
1182
1183         if (!clone_user.billing_address() &&
1184             !clone_user.mailing_address())
1185             return; // no addresses to copy or link
1186
1187         // if the cloned user has any addresses, we don't need 
1188         // the stub address created in init_new_patron.
1189         user.addresses = [];
1190
1191         var copy_addresses = 
1192             service.org_settings['circ.patron_edit.clone.copy_address'];
1193
1194         var clone_fields = [
1195             'day_phone',
1196             'evening_phone',
1197             'other_phone',
1198             'usrgroup'
1199         ]; 
1200
1201         angular.forEach(clone_fields, function(field) {
1202             user[field] = clone_user[field]();
1203         });
1204
1205         if (copy_addresses) {
1206             var bill_addr, mail_addr;
1207
1208             // copy the billing and mailing addresses into new addresses
1209             function clone_addr(addr) {
1210                 var new_addr = egCore.idl.toHash(addr);
1211                 new_addr.id = service.virt_id--;
1212                 new_addr.usr = user.id;
1213                 new_addr.isnew = true;
1214                 new_addr.valid = true;
1215                 user.addresses.push(new_addr);
1216                 return new_addr;
1217             }
1218
1219             if (bill_addr = clone_user.billing_address()) {
1220                 var addr = clone_addr(bill_addr);
1221                 addr._is_billing = true;
1222                 user.billing_address = addr;
1223             }
1224
1225             if (mail_addr = clone_user.mailing_address()) {
1226
1227                 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1228                     user.mailing_address = user.billing_address;
1229                     user.mailing_address._is_mailing = true;
1230                 } else {
1231                     var addr = clone_addr(mail_addr);
1232                     addr._is_mailing = true;
1233                     user.mailing_address = addr;
1234                 }
1235
1236                 if (!bill_addr) {
1237                     // if there is no billing addr, use the mailing addr
1238                     user.billing_address = user.mailing_address;
1239                     user.billing_address._is_billing = true;
1240                 }
1241             }
1242
1243
1244         } else {
1245
1246             // link the billing and mailing addresses
1247             var addr;
1248             if (addr = clone_user.billing_address()) {
1249                 user.billing_address = egCore.idl.toHash(addr);
1250                 user.billing_address._is_billing = true;
1251                 user.addresses.push(user.billing_address);
1252                 user.billing_address._linked_owner_id = clone_user.id();
1253                 user.billing_address._linked_owner = service.format_name(
1254                     clone_user.family_name(),
1255                     clone_user.first_given_name(),
1256                     clone_user.second_given_name()
1257                 );
1258             }
1259
1260             if (addr = clone_user.mailing_address()) {
1261                 if (user.billing_address && 
1262                     addr.id() == user.billing_address.id) {
1263                     // mailing matches billing
1264                     user.mailing_address = user.billing_address;
1265                     user.mailing_address._is_mailing = true;
1266                 } else {
1267                     user.mailing_address = egCore.idl.toHash(addr);
1268                     user.mailing_address._is_mailing = true;
1269                     user.addresses.push(user.mailing_address);
1270                     user.mailing_address._linked_owner_id = clone_user.id();
1271                     user.mailing_address._linked_owner = service.format_name(
1272                         clone_user.family_name(),
1273                         clone_user.first_given_name(),
1274                         clone_user.second_given_name()
1275                     );
1276                 }
1277             }
1278         }
1279     }
1280
1281     // translate the patron back into IDL form
1282     service.save_user = function(phash) {
1283
1284         var patron = egCore.idl.fromHash('au', phash);
1285
1286         patron.home_ou(patron.home_ou().id());
1287         patron.expire_date(patron.expire_date().toISOString());
1288         patron.profile(patron.profile().id());
1289         if (patron.dob()) 
1290             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1291         if (patron.ident_type()) 
1292             patron.ident_type(patron.ident_type().id());
1293         if (patron.net_access_level())
1294             patron.net_access_level(patron.net_access_level().id());
1295
1296         angular.forEach(
1297             ['juvenile', 'barred', 'active', 'master_account'],
1298             function(field) { patron[field](phash[field] ? 't' : 'f'); }
1299         );
1300
1301         var card_hashes = patron.cards();
1302         patron.cards([]);
1303         angular.forEach(card_hashes, function(chash) {
1304             var card = egCore.idl.fromHash('ac', chash)
1305             card.usr(patron.id());
1306             card.active(chash.active ? 't' : 'f');
1307             patron.cards().push(card);
1308             if (chash._primary) {
1309                 patron.card(card);
1310             }
1311         });
1312
1313         var addr_hashes = patron.addresses();
1314         patron.addresses([]);
1315         angular.forEach(addr_hashes, function(addr_hash) {
1316             if (!addr_hash.isnew && !addr_hash.isdeleted) 
1317                 addr_hash.ischanged = true;
1318             var addr = egCore.idl.fromHash('aua', addr_hash);
1319             patron.addresses().push(addr);
1320             addr.valid(addr.valid() ? 't' : 'f');
1321             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1322             if (addr_hash._is_mailing) patron.mailing_address(addr);
1323             if (addr_hash._is_billing) patron.billing_address(addr);
1324         });
1325
1326         patron.survey_responses([]);
1327         angular.forEach(service.survey_responses, function(answer) {
1328             var question = service.survey_questions[answer.question()];
1329             var resp = new egCore.idl.asvr();
1330             resp.isnew(true);
1331             resp.survey(question.survey());
1332             resp.question(question.id());
1333             resp.answer(answer.id());
1334             resp.usr(patron.id());
1335             resp.answer_date('now');
1336             patron.survey_responses().push(resp);
1337         });
1338         
1339         // re-object-ify the patron stat cat entry maps
1340         var maps = [];
1341         angular.forEach(patron.stat_cat_entries(), function(entry) {
1342             var e = egCore.idl.fromHash('actscecm', entry);
1343             e.stat_cat(e.stat_cat().id);
1344             maps.push(e);
1345         });
1346         patron.stat_cat_entries(maps);
1347
1348         // service.stat_cat_entry_maps maps stats to values
1349         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1350         angular.forEach(
1351             service.stat_cat_entry_maps, function(value, cat_id) {
1352
1353             // see if we already have a mapping for this entry
1354             var existing = patron.stat_cat_entries().filter(
1355                 function(e) { return e.stat_cat() == cat_id })[0];
1356
1357             if (existing) { // we have a mapping
1358                 // if the existing mapping matches the new one,
1359                 // there' nothing left to do
1360                 if (existing.stat_cat_entry() == value) return;
1361
1362                 // mappings differ.  delete the old one and create
1363                 // a new one below.
1364                 existing.isdeleted(true);
1365             }
1366
1367             var newmap = new egCore.idl.actscecm();
1368             newmap.target_usr(patron.id());
1369             newmap.isnew(true);
1370             newmap.stat_cat(cat_id);
1371             newmap.stat_cat_entry(value);
1372             patron.stat_cat_entries().push(newmap);
1373         });
1374
1375         if (!patron.isnew()) patron.ischanged(true);
1376
1377         return egLovefield.addOfflineXact({
1378             user        : egCore.idl.toHash(patron),
1379             timestamp   : parseInt(new Date().getTime() / 1000),
1380             type        : 'register',
1381             delta       : 0
1382         }).then(function (success) {
1383             if (success) return patron;
1384         });
1385     }
1386
1387     service.remove_staged_user = function() {
1388         if (!service.stage_user) return $q.when();
1389         return egCore.net.request(
1390             'open-ils.actor',
1391             'open-ils.actor.user.stage.delete',
1392             egCore.auth.token(),
1393             service.stage_user.user.row_id()
1394         );
1395     }
1396
1397     service.save_user_settings = function(new_user, user_settings) {
1398         return;
1399     }
1400
1401     // Applies field-specific validation regex's from org settings 
1402     // to form fields.  Be careful not remove any pattern data we
1403     // are not explicitly over-writing in the provided patterns obj.
1404     service.set_field_patterns = function(patterns) {
1405         if (service.org_settings['opac.username_regex']) {
1406             patterns.au.usrname = 
1407                 new RegExp(service.org_settings['opac.username_regex']);
1408         }
1409
1410         if (service.org_settings['opac.barcode_regex']) {
1411             patterns.ac.barcode = 
1412                 new RegExp(service.org_settings['opac.barcode_regex']);
1413         }
1414
1415         if (service.org_settings['global.password_regex']) {
1416             patterns.au.passwd = 
1417                 new RegExp(service.org_settings['global.password_regex']);
1418         }
1419
1420         var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1421         if (phone_reg) {
1422             // apply generic phone regex first, replace below as needed.
1423             patterns.au.day_phone = new RegExp(phone_reg);
1424             patterns.au.evening_phone = new RegExp(phone_reg);
1425             patterns.au.other_phone = new RegExp(phone_reg);
1426         }
1427
1428         // the remaining patterns fit a well-known key name pattern
1429
1430         angular.forEach(service.org_settings, function(val, key) {
1431             if (!val) return;
1432             var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1433             if (!parts) return;
1434             var cls = parts[1];
1435             var name = parts[2];
1436             patterns[cls][name] = new RegExp(val);
1437         });
1438     }
1439
1440     return service;
1441 }])
1442
1443 .controller('PatronRegCtrl',
1444        ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1445         'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1446         'egWorkLog','$timeout','egLovefield','$rootScope',
1447 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1448          patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1449          egWorkLog , $timeout , egLovefield , $rootScope) {
1450
1451     $scope.rs = $rootScope;
1452     if ($scope.workstation_obj) patronRegSvc.org = $scope.workstation_obj.owning_lib;
1453     $scope.offline = true;
1454
1455     $scope.page_data_loaded = false;
1456     $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1457     $scope.stage_username = 
1458         patronRegSvc.stage_username = $routeParams.stage_username;
1459     $scope.patron_id = 
1460         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1461
1462     // for existing patrons, disable barcode input by default
1463     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1464     $scope.focus_bc = !Boolean($scope.patron_id);
1465     $scope.address_alerts = [];
1466     $scope.dupe_counts = {};
1467
1468     // map of perm name to true/false for perms the logged in user
1469     // has at the currently selected patron home org unit.
1470     $scope.perms = {};
1471
1472     $scope.edit_passthru = {};
1473
1474     // 0=all, 1=suggested, 2=all
1475     $scope.edit_passthru.vis_level = 2; 
1476
1477     // Apply default values for new patrons during initial registration
1478     // prs is shorthand for patronSvc
1479     function set_new_patron_defaults(prs) {
1480         if (!$scope.patron.passwd) {
1481             // passsword may originate from staged user.
1482             $scope.generate_password();
1483         }
1484         $scope.hold_notify_phone = true;
1485         $scope.hold_notify_email = true;
1486
1487         // staged users may be loaded w/ a profile.
1488         $scope.set_expire_date();
1489
1490         if (prs.org_settings['ui.patron.default_ident_type']) {
1491             // $scope.patron needs this field to be an object
1492             var id = prs.org_settings['ui.patron.default_ident_type'];
1493             var ident_type = $scope.ident_types.filter(
1494                 function(type) { return type.id() == id })[0];
1495             $scope.patron.ident_type = ident_type;
1496         }
1497         if (prs.org_settings['ui.patron.default_inet_access_level']) {
1498             // $scope.patron needs this field to be an object
1499             var id = prs.org_settings['ui.patron.default_inet_access_level'];
1500             var level = $scope.net_access_levels.filter(
1501                 function(lvl) { return lvl.id() == id })[0];
1502             $scope.patron.net_access_level = level;
1503         }
1504         if (prs.org_settings['ui.patron.default_country']) {
1505             $scope.patron.addresses[0].country = 
1506                 prs.org_settings['ui.patron.default_country'];
1507         }
1508     }
1509
1510     // A null or undefined pattern leads to exceptions.  Before the
1511     // patterns are loaded from the server, default all patterns
1512     // to an innocuous regex.  To avoid re-creating numerous
1513     // RegExp objects, cache the stub RegExp after initial creation.
1514     // note: angular docs say ng-pattern accepts a regexp or string,
1515     // but as of writing, it only works with a regexp object.
1516     // (Likely an angular 1.2 vs. 1.4 issue).
1517     var field_patterns = {au : {}, ac : {}, aua : {}};
1518     $scope.field_pattern = function(cls, field) { 
1519         if (!field_patterns[cls][field])
1520             field_patterns[cls][field] = new RegExp('.*');
1521         return field_patterns[cls][field];
1522     }
1523
1524     patronRegSvc.offlineMode($scope.offline); // force offline if ng-init'd to do so
1525     patronRegSvc.init().then(function() {
1526         // called after initTab and patronRegSvc.init have completed
1527     
1528         var prs = patronRegSvc; // brevity
1529         // in standalone mode, we have no patronSvc
1530         $scope.patron = prs.init_patron(patronSvc ? patronSvc.current : null);
1531         $scope.field_doc = prs.field_doc;
1532         $scope.edit_profiles = prs.edit_profiles;
1533         $scope.ident_types = prs.ident_types;
1534         $scope.net_access_levels = prs.net_access_levels;
1535         $scope.user_setting_types = prs.user_setting_types;
1536         $scope.opt_in_setting_types = prs.opt_in_setting_types;
1537         $scope.org_settings = prs.org_settings;
1538         $scope.sms_carriers = prs.sms_carriers;
1539         $scope.stat_cats = prs.stat_cats;
1540         $scope.surveys = prs.surveys;
1541         $scope.survey_responses = prs.survey_responses;
1542         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1543         $scope.stage_user = prs.stage_user;
1544         $scope.stage_user_requestor = prs.stage_user_requestor;
1545     
1546         $scope.user_settings = prs.user_settings;
1547         // clone the user settings back into the patronRegSvc so
1548         // we have a copy of the original state of the settings.
1549         prs.user_settings = {};
1550         angular.forEach($scope.user_settings, function(val, key) {
1551             prs.user_settings[key] = val;
1552         });
1553     
1554         extract_hold_notify();
1555         $scope.handle_home_org_changed();
1556     
1557         if ($scope.org_settings['ui.patron.edit.default_suggested'])
1558             $scope.edit_passthru.vis_level = 1;
1559     
1560         if ($scope.patron.isnew) 
1561             set_new_patron_defaults(prs);
1562     
1563         $scope.page_data_loaded = true;
1564     
1565         prs.set_field_patterns(field_patterns);
1566         apply_username_regex();
1567     });
1568
1569     // update the currently displayed field documentation
1570     $scope.set_selected_field_doc = function(cls, field) {
1571         $scope.selected_field_doc = $scope.field_doc[cls][field];
1572     }
1573
1574     // returns the tree depth of the selected profile group tree node.
1575     $scope.pgt_depth = function(grp) {
1576         var d = 0;
1577         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1578         return d;
1579     }
1580
1581     // IDL fields used for labels in the UI.
1582     $scope.idl_fields = {
1583         au  : egCore.idl.classes.au.field_map,
1584         ac  : egCore.idl.classes.ac.field_map,
1585         aua : egCore.idl.classes.aua.field_map
1586     };
1587
1588     // field visibility cache.  Some fields are universally required.
1589     // 3 == value universally required
1590     // 2 == field is visible by default
1591     // 1 == field is suggested by default
1592     var field_visibility = {};
1593     var default_field_visibility = {
1594         'ac.barcode' : 3,
1595         'au.usrname' : 3,
1596         'au.passwd' :  3,
1597         'au.first_given_name' : 3,
1598         'au.family_name' : 3,
1599         'au.ident_type' : 3,
1600         'au.home_ou' : 3,
1601         'au.profile' : 3,
1602         'au.expire_date' : 3,
1603         'au.net_access_level' : 3,
1604         'aua.address_type' : 3,
1605         'aua.post_code' : 3,
1606         'aua.street1' : 3,
1607         'aua.street2' : 2,
1608         'aua.city' : 3,
1609         'aua.county' : 2,
1610         'aua.state' : 2,
1611         'aua.country' : 3,
1612         'aua.valid' : 2,
1613         'aua.within_city_limits' : 2,
1614         'stat_cats' : 1,
1615         'surveys' : 1
1616     }; 
1617
1618     // Returns true if the selected field should be visible
1619     // given the current required/suggested/all setting.
1620     // The visibility flag applied to each field as a result of calling
1621     // this function also sets (via the same flag) the requiredness state.
1622     $scope.show_field = function(field_key) {
1623         // org settings have not been received yet.
1624         if (!$scope.org_settings) return false;
1625
1626         if (field_visibility[field_key] == undefined) {
1627             // compile and cache the visibility for the selected field
1628
1629             var req_set = 'ui.patron.edit.' + field_key + '.require';
1630             var sho_set = 'ui.patron.edit.' + field_key + '.show';
1631             var sug_set = 'ui.patron.edit.' + field_key + '.suggest';
1632
1633             if ($scope.org_settings[req_set]) {
1634                 field_visibility[field_key] = 3;
1635
1636             } else if ($scope.org_settings[sho_set]) {
1637                 field_visibility[field_key] = 2;
1638
1639             } else if ($scope.org_settings[sug_set]) {
1640                 field_visibility[field_key] = 1;
1641             }
1642         }
1643
1644         if (field_visibility[field_key] == undefined) {
1645             // No org settings were applied above.  Use the default
1646             // settings if present or assume the field has no
1647             // visibility flags applied.
1648             field_visibility[field_key] = 
1649                 default_field_visibility[field_key] || 0;
1650         }
1651
1652         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1653     }
1654
1655     // See $scope.show_field().
1656     // A field with visbility level 3 means it's required.
1657     $scope.field_required = function(cls, field) {
1658
1659         // Value in the password field is not required
1660         // for existing patrons.
1661         if (field == 'passwd' && $scope.patron && !$scope.patron.isnew) 
1662           return false;
1663
1664         return (field_visibility[cls + '.' + field] == 3 || default_field_visibility[cls + '.' + field] == 3);
1665     }
1666
1667     // generates a random 4-digit password
1668     $scope.generate_password = function() {
1669         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1670     }
1671
1672     $scope.set_expire_date = function() {
1673         if (!$scope.patron.profile) return;
1674         var seconds = egCore.date.intervalToSeconds(
1675             $scope.patron.profile.perm_interval());
1676         var now_epoch = new Date().getTime();
1677         $scope.patron.expire_date = new Date(
1678             now_epoch + (seconds * 1000 /* milliseconds */))
1679     }
1680
1681     // grp is the pgt object
1682     $scope.set_profile = function(grp) {
1683         $scope.patron.profile = grp;
1684         $scope.set_expire_date();
1685         $scope.field_modified();
1686     }
1687
1688     $scope.invalid_profile = function() {
1689         return !(
1690             $scope.patron && 
1691             $scope.patron.profile && 
1692             $scope.patron.profile.usergroup() == 't'
1693         );
1694     }
1695
1696     $scope.new_address = function() {
1697         var addr = egCore.idl.toHash(new egCore.idl.aua());
1698         patronRegSvc.ingest_address($scope.patron, addr);
1699         addr.id = patronRegSvc.virt_id--;
1700         addr.isnew = true;
1701         addr.valid = true;
1702         addr.within_city_limits = true;
1703         addr.country = $scope.org_settings['ui.patron.default_country'];
1704         $scope.patron.addresses.push(addr);
1705     }
1706
1707     // keep deleted addresses out of the patron object so
1708     // they won't appear in the UI.  They'll be re-inserted
1709     // when the patron is updated.
1710     deleted_addresses = [];
1711     $scope.delete_address = function(id) {
1712
1713         if ($scope.patron.isnew &&
1714             $scope.patron.addresses.length == 1 &&
1715             $scope.org_settings['ui.patron.registration.require_address']) {
1716             egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1717             return;
1718         }
1719
1720         var addresses = [];
1721         angular.forEach($scope.patron.addresses, function(addr) {
1722             if (addr.id == id) {
1723                 if (id > 0) {
1724                     addr.isdeleted = true;
1725                     deleted_addresses.push(addr);
1726                 }
1727             } else {
1728                 addresses.push(addr);
1729             }
1730         });
1731         $scope.patron.addresses = addresses;
1732     } 
1733
1734     $scope.post_code_changed = function(addr) { 
1735         if ($scope.offline) return;
1736         egCore.net.request(
1737             'open-ils.search', 'open-ils.search.zip', addr.post_code)
1738         .then(function(resp) {
1739             if (!resp) return;
1740             if (resp.city) addr.city = resp.city;
1741             if (resp.state) addr.state = resp.state;
1742             if (resp.county) addr.county = resp.county;
1743             if (resp.alert) alert(resp.alert);
1744         });
1745     }
1746
1747     $scope.replace_card = function() {
1748         $scope.patron.card.active = false;
1749         $scope.patron.card.ischanged = true;
1750         $scope.disable_bc = false;
1751
1752         var new_card = egCore.idl.toHash(new egCore.idl.ac());
1753         new_card.id = patronRegSvc.virt_id--;
1754         new_card.isnew = true;
1755         new_card.active = true;
1756         new_card._primary = 'on';
1757         $scope.patron.card = new_card;
1758         $scope.patron.cards.push(new_card);
1759     }
1760
1761     $scope.day_phone_changed = function(phone) {
1762         if (phone && $scope.patron.isnew && 
1763             $scope.org_settings['patron.password.use_phone']) {
1764             $scope.patron.passwd = phone.substr(-4);
1765         }
1766     }
1767
1768     $scope.barcode_changed = function(bc) {
1769         if (!bc) return;
1770         if (!$scope.patron.usrname)
1771             $scope.patron.usrname = bc;
1772     }
1773
1774     $scope.cards_dialog = function() {
1775         $uibModal.open({
1776             templateUrl: './circ/patron/t_patron_cards_dialog',
1777             controller: 
1778                    ['$scope','$uibModalInstance','cards','perms',
1779             function($scope , $uibModalInstance , cards , perms) {
1780                 // scope here is the modal-level scope
1781                 $scope.args = {cards : cards};
1782                 $scope.perms = perms;
1783                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1784                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1785             }],
1786             resolve : {
1787                 cards : function() {
1788                     // scope here is the controller-level scope
1789                     return $scope.patron.cards;
1790                 },
1791                 perms : function() {
1792                     return $scope.perms;
1793                 }
1794             }
1795         }).result.then(
1796             function(args) {
1797                 angular.forEach(args.cards, function(card) {
1798                     card.ischanged = true; // assume cards need updating, OK?
1799                     if (card._primary == 'on' && 
1800                         card.id != $scope.patron.card.id) {
1801                         $scope.patron.card = card;
1802                     }
1803                 });
1804             }
1805         );
1806     }
1807
1808     $scope.set_addr_type = function(addr, type) {
1809         var addrs = $scope.patron.addresses;
1810         if (addr['_is_'+type]) {
1811             angular.forEach(addrs, function(a) {
1812                 if (a.id != addr.id) a['_is_'+type] = false;
1813             });
1814         } else {
1815             // unchecking mailing/billing means we have to randomly
1816             // select another address to fill that role.  Select the
1817             // first address in the list (that does not match the
1818             // modifed address)
1819             for (var i = 0; i < addrs.length; i++) {
1820                 if (addrs[i].id != addr.id) {
1821                     addrs[i]['_is_' + type] = true;
1822                     break;
1823                 }
1824             }
1825         }
1826     }
1827
1828
1829     // Translate hold notify preferences from the form/scope back into a 
1830     // single user setting value for opac.hold_notify.
1831     function compress_hold_notify() {
1832         var hold_notify = '';
1833         var splitter = '';
1834         if ($scope.hold_notify_phone) {
1835             hold_notify = 'phone';
1836             splitter = ':';
1837         }
1838         if ($scope.hold_notify_email) {
1839             hold_notify = splitter + 'email';
1840             splitter = ':';
1841         }
1842         if ($scope.hold_notify_sms) {
1843             hold_notify = splitter + 'sms';
1844             splitter = ':';
1845         }
1846         $scope.user_settings['opac.hold_notify'] = hold_notify;
1847     }
1848
1849     // dialog for selecting additional permission groups
1850     $scope.secondary_groups_dialog = function() {
1851         $uibModal.open({
1852             templateUrl: './circ/patron/t_patron_groups_dialog',
1853             controller: 
1854                    ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1855             function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1856
1857                 $scope.pgt_depth = pgt_depth;
1858                 $scope.args = {
1859                     linked_groups : linked_groups,
1860                     edit_profiles : patronRegSvc.edit_profiles,
1861                     new_profile   : patronRegSvc.edit_profiles[0]
1862                 };
1863
1864                 // add a new group to the linked groups list
1865                 $scope.link_group = function($event, grp) {
1866                     var found = false; // avoid duplicates
1867                     angular.forEach($scope.args.linked_groups, 
1868                         function(g) {if (g.id() == grp.id()) found = true});
1869                     if (!found) $scope.args.linked_groups.push(grp);
1870                     $event.preventDefault(); // avoid close
1871                 }
1872
1873                 // remove a group from the linked groups list
1874                 $scope.unlink_group = function($event, grp) {
1875                     $scope.args.linked_groups = 
1876                         $scope.args.linked_groups.filter(function(g) {
1877                         return g.id() != grp.id()
1878                     });
1879                     $event.preventDefault(); // avoid close
1880                 }
1881
1882                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1883                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1884             }],
1885             resolve : {
1886                 linked_groups : function() { return $scope.patron.groups },
1887                 pgt_depth : function() { return $scope.pgt_depth }
1888             }
1889         }).result.then(
1890             function(args) {
1891
1892                 if ($scope.patron.isnew) {
1893                     // groups must be linked for new patrons after the
1894                     // patron is created.
1895                     $scope.patron.groups = args.linked_groups;
1896                     return;
1897                 }
1898
1899                 // update links groups for existing users in real time.
1900                 var ids = args.linked_groups.map(function(g) {return g.id()});
1901                 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1902                 .then(function(success) {
1903                     if (success)
1904                         $scope.patron.groups = args.linked_groups;
1905                 });
1906             }
1907         );
1908     }
1909
1910     function extract_hold_notify() {
1911         notify = $scope.user_settings['opac.hold_notify'];
1912         if (!notify) return;
1913         $scope.hold_notify_phone = Boolean(notify.match(/phone/));
1914         $scope.hold_notify_email = Boolean(notify.match(/email/));
1915         $scope.hold_notify_sms = Boolean(notify.match(/sms/));
1916     }
1917
1918     $scope.invalidate_field = function(field) {
1919         patronRegSvc.invalidate_field($scope.patron, field);
1920     }
1921
1922     address_alert = function(addr) {
1923         if ($scope.offline) return;
1924         var args = {
1925             street1: addr.street1,
1926             street2: addr.street2,
1927             city: addr.city,
1928             state: addr.state,
1929             county: addr.county,
1930             country: addr.country,
1931             post_code: addr.post_code,
1932             mailing_address: addr._is_mailing,
1933             billing_address: addr._is_billing
1934         }
1935
1936         egCore.net.request(
1937             'open-ils.actor',
1938             'open-ils.actor.address_alert.test',
1939             egCore.auth.token(), egCore.auth.user().ws_ou(), args
1940             ).then(function(res) {
1941                 $scope.address_alerts = res;
1942         });
1943     }
1944
1945     $scope.dupe_value_changed = function(type, value) {
1946         $scope.dupe_counts[type] = 0;
1947         patronRegSvc.dupe_patron_search($scope.patron, type, value)
1948         .then(function(res) {
1949             $scope.dupe_counts[type] = res.count;
1950             if (res.count) {
1951                 $scope.dupe_search_encoded = 
1952                     encodeURIComponent(js2JSON(res.search));
1953             } else {
1954                 $scope.dupe_search_encoded = '';
1955             }
1956         });
1957     }
1958
1959     // Dummy function in offline mode
1960     $scope.handle_home_org_changed = function() {}
1961
1962     // This is called with every character typed in a form field,
1963     // since that's the only way to gaurantee something has changed.
1964     // See handle_field_changed for ng-change vs. ng-blur.
1965     $scope.field_modified = function() {
1966         // Call attach with every field change, regardless of whether
1967         // it's been called before.  This will allow for re-attach after
1968         // the user clicks through the unload warning. egUnloadPrompt
1969         // will ensure we only attach once.
1970         egUnloadPrompt.attach($rootScope);
1971     }
1972
1973     // also monitor when form is changed *by the user*, as using
1974     // an ng-change handler doesn't work with eg-date-input
1975     $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
1976         if (!newVal) egUnloadPrompt.attach($rootScope);
1977     });
1978
1979     // username regex (if present) must be removed any time
1980     // the username matches the barcode to avoid firing the
1981     // invalid field handlers.
1982     function apply_username_regex() {
1983         var regex = $scope.org_settings['opac.username_regex'];
1984         if (regex) {
1985             if ($scope.patron.card.barcode) {
1986                 // username must match the regex or the barcode
1987                 field_patterns.au.usrname = 
1988                     new RegExp(
1989                         regex + '|^' + $scope.patron.card.barcode + '$');
1990             } else {
1991                 // username must match the regex
1992                 field_patterns.au.usrname = new RegExp(regex);
1993             }
1994         } else {
1995             // username can be any format.
1996             field_patterns.au.usrname = new RegExp('.*');
1997         }
1998     }
1999
2000     // obj could be the patron, an address, etc.
2001     // This is called any time a form field achieves then loses focus.
2002     // It does not necessarily mean the field has changed.
2003     // The alternative is ng-change, but it's called with each character
2004     // typed, which would be overkill for many of the actions called here.
2005     $scope.handle_field_changed = function(obj, field_name) {
2006         if (!obj) return;
2007
2008         var cls = obj.classname; // set by egIdl
2009         var value = obj[field_name];
2010
2011         // Hush!
2012         //console.log('changing field ' + field_name + ' to ' + value);
2013
2014         switch (field_name) {
2015             case 'day_phone' : 
2016                 if ($scope.patron.day_phone && 
2017                     $scope.patron.isnew && 
2018                     $scope.org_settings['patron.password.use_phone']) {
2019                     $scope.patron.passwd = phone.substr(-4);
2020                 }
2021                 break;
2022
2023             case 'barcode':
2024                 apply_username_regex();
2025                 $scope.barcode_changed(value);
2026                 break;
2027
2028             case 'dob':
2029                 maintain_juvenile_flag();
2030                 break;
2031
2032             default:
2033                 break;
2034         }
2035     }
2036
2037     // patron.juvenile is set to true if the user was born after
2038     function maintain_juvenile_flag() {
2039         if ( !($scope.patron && $scope.patron.dob) ) return;
2040
2041         var juv_interval = 
2042             $scope.org_settings['global.juvenile_age_threshold'] 
2043             || '18 years';
2044
2045         var base = new Date();
2046
2047         base.setTime(base.getTime() - 
2048             Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2049
2050         $scope.patron.juvenile = ($scope.patron.dob > base);
2051     }
2052
2053     // returns true (disable) for orgs that cannot have users.
2054     $scope.disable_home_org = function(org_id) {
2055         if (!org_id) return;
2056         var org = egCore.org.get(org_id);
2057         return (
2058             org &&
2059             org.ou_type() &&
2060             org.ou_type().can_have_users() == 'f'
2061         );
2062     }
2063
2064     // Returns true if the Save and Save & Clone buttons should be disabled.
2065     $scope.edit_passthru.hide_save_actions = function() {
2066         return false;
2067     }
2068
2069     // Returns true if any input elements are tagged as invalid
2070     // via Angular patterns or required attributes.
2071     function form_has_invalid_fields() {
2072         return $('#patron-reg-container .ng-invalid').length > 0;
2073     }
2074
2075     function form_is_incomplete() {
2076         return (
2077             $scope.dupe_username ||
2078             $scope.dupe_barcode ||
2079             form_has_invalid_fields()
2080         );
2081
2082     }
2083
2084     $scope.edit_passthru.save = function(save_args) {
2085         if (!save_args) save_args = {};
2086
2087         if (form_is_incomplete()) {
2088             // User has not provided valid values for all required fields.
2089             return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2090         }
2091
2092         // remove page unload warning prompt
2093         egUnloadPrompt.clear();
2094
2095         // toss the deleted addresses back into the patron's list of
2096         // addresses so it's included in the update
2097         $scope.patron.addresses = 
2098             $scope.patron.addresses.concat(deleted_addresses);
2099         
2100         compress_hold_notify();
2101
2102         var updated_user;
2103
2104         patronRegSvc.save_user($scope.patron)
2105         .then($scope.rs.save_offline_xacts)
2106         .then(function(new_user) { 
2107             // reload the current page
2108             $window.location.href = location.href;
2109         });
2110     }
2111 }])