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