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