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