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