]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/regctl.js
LP#1264746 Add "email password reset" to user editor
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / regctl.js
1
2 angular.module('egCoreMod')
3 // toss tihs onto egCoreMod since the page app may vary
4
5 .factory('patronRegSvc', ['$q', '$filter', 'egCore', 'egLovefield', function($q, $filter, egCore, egLovefield) {
6
7     var service = {
8         field_doc : {},            // config.idl_field_doc
9         profiles : [],             // permission groups
10         profile_entries : [],      // permission gorup display entries
11         edit_profiles : [],        // perm groups we can modify
12         edit_profile_entries : [], // perm group display entries we can modify
13         sms_carriers : [],
14         user_settings : {},        // applied user settings
15         user_setting_types : {},   // config.usr_setting_type
16         opt_in_setting_types : {}, // config.usr_setting_type for event-def opt-in
17         surveys : [],
18         survey_questions : {},
19         survey_answers : {},
20         survey_responses : {},     // survey.responses for loaded patron in progress
21         stat_cats : [],
22         stat_cat_entry_maps : {},   // cat.id to selected value
23         virt_id : -1,               // virtual ID for new objects
24         init_done : false           // have we loaded our initialization data?
25     };
26
27     // Launch a series of parallel data retrieval calls.
28     service.init = function(scope) {
29
30         // These are fetched with every instance of the page.
31         var page_data = [
32             service.get_user_settings(),
33             service.get_clone_user(),
34             service.get_stage_user()
35         ];
36
37         var common_data = [];
38         if (!service.init_done) {
39             // These are fetched with every instance of the app.
40             common_data = [
41                 service.get_field_doc(),
42                 service.get_perm_groups(),
43                 service.get_perm_group_entries(),
44                 service.get_ident_types(),
45                 service.get_org_settings(),
46                 service.get_stat_cats(),
47                 service.get_surveys(),
48                 service.get_net_access_levels()
49             ];
50             service.init_done = true;
51         }
52
53         return $q.all(common_data.concat(page_data));
54     };
55
56     service.get_clone_user = function() {
57         if (!service.clone_id) return $q.when();
58         // we could load egUser and use its get() function, but loading
59         // user.js into the standalone register UI would mean creating a
60         // new module, since egUser is not loaded into egCoreMod.  This
61         // is a lot simpler.
62         return egCore.net.request(
63             'open-ils.actor',
64             'open-ils.actor.user.fleshed.retrieve',
65             egCore.auth.token(), service.clone_id, 
66             ['billing_address', 'mailing_address'])
67         .then(function(cuser) {
68             if (e = egCore.evt.parse(cuser)) {
69                 alert(e);
70             } else {
71                 service.clone_user = cuser;
72             }
73         });
74     }
75
76     // When editing a user with addresses linked to other users, fetch
77     // the linked user(s) so we can display their names and edit links.
78     service.get_linked_addr_users = function(addrs) {
79         angular.forEach(addrs, function(addr) {
80             if (addr.usr == service.existing_patron.id()) return;
81             egCore.pcrud.retrieve('au', addr.usr)
82             .then(function(usr) {
83                 addr._linked_owner_id = usr.id();
84                 addr._linked_owner = service.format_name(
85                     usr.family_name(),
86                     usr.first_given_name(),
87                     usr.second_given_name()
88                 );
89             })
90         });
91     }
92
93     service.apply_secondary_groups = function(user_id, group_ids) {
94         return egCore.net.request(
95             'open-ils.actor',
96             'open-ils.actor.user.set_groups',
97             egCore.auth.token(), user_id, group_ids)
98         .then(function(resp) {
99             if (resp == 1) {
100                 return true;
101             } else {
102                 // debugging -- should be no events
103                 alert('linked groups failure ' + egCore.evt.parse(resp));
104             }
105         });
106     }
107
108     service.get_stage_user = function() {
109         if (!service.stage_username) return $q.when();
110
111         // fetch the staged user object
112         return egCore.net.request(
113             'open-ils.actor',
114             'open-ils.actor.user.stage.retrieve.by_username',
115             egCore.auth.token(), 
116             service.stage_username
117         ).then(function(suser) {
118             if (e = egCore.evt.parse(suser)) {
119                 alert(e);
120             } else {
121                 service.stage_user = suser;
122             }
123         }).then(function() {
124
125             if (!service.stage_user) return;
126             var requestor = service.stage_user.user.requesting_usr();
127
128             if (!requestor) return;
129
130             // fetch the requesting user
131             return egCore.net.request(
132                 'open-ils.actor', 
133                 'open-ils.actor.user.retrieve.parts',
134                 egCore.auth.token(),
135                 requestor, 
136                 ['family_name', 'first_given_name', 'second_given_name'] 
137             ).then(function(parts) {
138                 service.stage_user_requestor = 
139                     service.format_name(parts[0], parts[1], parts[2]);
140             })
141         });
142     }
143
144     // See note above about not loading egUser.
145     // TODO: i18n
146     service.format_name = function(last, first, middle) {
147         return last + ', ' + first + (middle ? ' ' + middle : '');
148     }
149
150     service.check_dupe_username = function(usrname) {
151
152         // empty usernames can't be dupes
153         if (!usrname) return $q.when(false);
154
155         // avoid dupe check if username matches the originally loaded usrname
156         if (service.existing_patron) {
157             if (usrname == service.existing_patron.usrname())
158                 return $q.when(false);
159         }
160
161         return egCore.net.request(
162             'open-ils.actor',
163             'open-ils.actor.username.exists',
164             egCore.auth.token(), usrname);
165     }
166
167     // compare string with email address of loaded user, return true if different
168     service.check_email_different = function(email) {
169         if (service.existing_patron) {
170             if (email != service.existing_patron.email()) {
171                 return $q.when(true);
172             }
173         }
174     }
175
176     //service.check_grp_app_perm = function(grp_id) {
177
178     // determine which user groups our user is not allowed to modify
179     service.set_edit_profiles = function() {
180         var all_app_perms = [];
181         var failed_perms = [];
182
183         // extract the application permissions
184         angular.forEach(service.profiles, function(grp) {
185             if (grp.application_perm())
186                 all_app_perms.push(grp.application_perm());
187         }); 
188
189         // fill in service.edit_profiles by inspecting failed_perms
190         function traverse_grp_tree(grp, failed) {
191             failed = failed || 
192                 failed_perms.indexOf(grp.application_perm()) > -1;
193
194             if (!failed) service.edit_profiles.push(grp);
195
196             angular.forEach(
197                 service.profiles.filter( // children of grp
198                     function(p) { return p.parent() == grp.id() }),
199                 function(child) {traverse_grp_tree(child, failed)}
200             );
201         }
202
203         return egCore.perm.hasPermAt(all_app_perms, true).then(
204             function(perm_orgs) {
205                 angular.forEach(all_app_perms, function(p) {
206                     if (perm_orgs[p].length == 0)
207                         failed_perms.push(p);
208                 });
209
210                 traverse_grp_tree(egCore.env.pgt.tree);
211             }
212         );
213     }
214
215     service.set_edit_profile_entries = function() {
216         var all_app_perms = [];
217         var failed_perms = [];
218
219         // extract the application permissions
220         angular.forEach(service.profile_entries, function(entry) {
221             if (entry.grp().application_perm())
222                 all_app_perms.push(entry.grp().application_perm());
223         });
224
225         // fill in service.edit_profiles by inspecting failed_perms
226         function traverse_grp_tree(entry, failed) {
227             failed = failed ||
228                 failed_perms.indexOf(entry.grp().application_perm()) > -1;
229
230             if (!failed) service.edit_profile_entries.push(entry);
231
232             angular.forEach(
233                 service.profile_entries.filter( // children of grp
234                     function(p) { return p.parent() == entry.id() }),
235                 function(child) {traverse_grp_tree(child, failed)}
236             );
237         }
238
239         return egCore.perm.hasPermAt(all_app_perms, true).then(
240             function(perm_orgs) {
241                 angular.forEach(all_app_perms, function(p) {
242                     if (perm_orgs[p].length == 0)
243                         failed_perms.push(p);
244                 });
245
246                 angular.forEach(egCore.env.pgtde.tree, function(tree) {
247                     traverse_grp_tree(tree);
248                 });
249             }
250         );
251     }
252
253     // resolves to a hash of perm-name => boolean value indicating
254     // wether the user has the permission at org_id.
255     service.has_perms_for_org = function(org_id) {
256
257         var perms_needed = [
258             'EDIT_SELF_IN_CLIENT',
259             'UPDATE_USER',
260             'CREATE_USER',
261             'CREATE_USER_GROUP_LINK', 
262             'UPDATE_PATRON_COLLECTIONS_EXEMPT',
263             'UPDATE_PATRON_CLAIM_RETURN_COUNT',
264             'UPDATE_PATRON_CLAIM_NEVER_CHECKED_OUT_COUNT',
265             'UPDATE_PATRON_ACTIVE_CARD',
266             'UPDATE_PATRON_PRIMARY_CARD'
267         ];
268
269         return egCore.perm.hasPermAt(perms_needed, true)
270         .then(function(perm_map) {
271
272             angular.forEach(perms_needed, function(perm) {
273                 perm_map[perm] = 
274                     Boolean(perm_map[perm].indexOf(org_id) > -1);
275             });
276
277             return perm_map;
278         });
279     }
280
281     service.get_surveys = function() {
282         var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
283
284         return egCore.pcrud.search('asv', {
285                 owner : org_ids,
286                 start_date : {'<=' : 'now'},
287                 end_date : {'>=' : 'now'}
288             }, {   
289                 flesh : 2, 
290                 flesh_fields : {
291                     asv : ['questions'], 
292                     asvq : ['answers']
293                 }
294             }, 
295             {atomic : true}
296         ).then(function(surveys) {
297             surveys = surveys.sort(function(a,b) {
298                 return a.name() < b.name() ? -1 : 1 });
299             service.surveys = surveys;
300             angular.forEach(surveys, function(survey) {
301                 angular.forEach(survey.questions(), function(question) {
302                     service.survey_questions[question.id()] = question;
303                     angular.forEach(question.answers(), function(answer) {
304                         service.survey_answers[answer.id()] = answer;
305                     });
306                 });
307             });
308
309             egLovefield.setListInOfflineCache('asv', service.surveys)
310             egLovefield.setListInOfflineCache('asvq', service.survey_questions)
311             egLovefield.setListInOfflineCache('asva', service.survey_answers)
312
313         });
314     }
315
316     service.get_stat_cats = function() {
317         return egCore.net.request(
318             'open-ils.circ',
319             'open-ils.circ.stat_cat.actor.retrieve.all',
320             egCore.auth.token(), egCore.auth.user().ws_ou()
321         ).then(function(cats) {
322             cats = cats.sort(function(a, b) {
323                 return a.name() < b.name() ? -1 : 1});
324             angular.forEach(cats, function(cat) {
325                 cat.entries(
326                     cat.entries().sort(function(a,b) {
327                         return a.value() < b.value() ? -1 : 1
328                     })
329                 );
330             });
331             service.stat_cats = cats;
332             return egLovefield.setStatCatsCache(cats);
333         });
334     };
335
336     service.get_org_settings = function() {
337         return egCore.org.settings([
338             'global.password_regex',
339             'global.juvenile_age_threshold',
340             'patron.password.use_phone',
341             'ui.patron.default_inet_access_level',
342             'ui.patron.default_ident_type',
343             'ui.patron.default_country',
344             'ui.patron.registration.require_address',
345             'circ.holds.behind_desk_pickup_supported',
346             'circ.patron_edit.clone.copy_address',
347             'circ.privacy_waiver',
348             'ui.patron.edit.au.prefix.require',
349             'ui.patron.edit.au.prefix.show',
350             'ui.patron.edit.au.prefix.suggest',
351             'ui.patron.edit.ac.barcode.regex',
352             'ui.patron.edit.au.second_given_name.show',
353             'ui.patron.edit.au.second_given_name.suggest',
354             'ui.patron.edit.au.suffix.show',
355             'ui.patron.edit.au.suffix.suggest',
356             'ui.patron.edit.au.alias.show',
357             'ui.patron.edit.au.alias.suggest',
358             'ui.patron.edit.au.dob.require',
359             'ui.patron.edit.au.dob.show',
360             'ui.patron.edit.au.dob.suggest',
361             'ui.patron.edit.au.dob.calendar',
362             'ui.patron.edit.au.dob.example',
363             'ui.patron.edit.au.juvenile.show',
364             'ui.patron.edit.au.juvenile.suggest',
365             'ui.patron.edit.au.ident_value.show',
366             'ui.patron.edit.au.ident_value.require',
367             'ui.patron.edit.au.ident_value.suggest',
368             'ui.patron.edit.au.ident_value2.show',
369             'ui.patron.edit.au.ident_value2.suggest',
370             'ui.patron.edit.au.photo_url.require',
371             'ui.patron.edit.au.photo_url.show',
372             'ui.patron.edit.au.photo_url.suggest',
373             'ui.patron.edit.au.email.require',
374             'ui.patron.edit.au.email.show',
375             'ui.patron.edit.au.email.suggest',
376             'ui.patron.edit.au.email.regex',
377             'ui.patron.edit.au.email.example',
378             'ui.patron.edit.au.day_phone.require',
379             'ui.patron.edit.au.day_phone.show',
380             'ui.patron.edit.au.day_phone.suggest',
381             'ui.patron.edit.au.day_phone.regex',
382             'ui.patron.edit.au.day_phone.example',
383             'ui.patron.edit.au.evening_phone.require',
384             'ui.patron.edit.au.evening_phone.show',
385             'ui.patron.edit.au.evening_phone.suggest',
386             'ui.patron.edit.au.evening_phone.regex',
387             'ui.patron.edit.au.evening_phone.example',
388             'ui.patron.edit.au.other_phone.require',
389             'ui.patron.edit.au.other_phone.show',
390             'ui.patron.edit.au.other_phone.suggest',
391             'ui.patron.edit.au.other_phone.regex',
392             'ui.patron.edit.au.other_phone.example',
393             'ui.patron.edit.phone.regex',
394             'ui.patron.edit.phone.example',
395             'ui.patron.edit.au.active.show',
396             'ui.patron.edit.au.active.suggest',
397             'ui.patron.edit.au.barred.show',
398             'ui.patron.edit.au.barred.suggest',
399             'ui.patron.edit.au.master_account.show',
400             'ui.patron.edit.au.master_account.suggest',
401             'ui.patron.edit.au.claims_returned_count.show',
402             'ui.patron.edit.au.claims_returned_count.suggest',
403             'ui.patron.edit.au.claims_never_checked_out_count.show',
404             'ui.patron.edit.au.claims_never_checked_out_count.suggest',
405             'ui.patron.edit.au.alert_message.show',
406             'ui.patron.edit.au.alert_message.suggest',
407             'ui.patron.edit.aua.post_code.regex',
408             'ui.patron.edit.aua.post_code.example',
409             'ui.patron.edit.aua.county.require',
410             'ui.patron.edit.au.guardian.show',
411             'ui.patron.edit.au.guardian.suggest',
412             'ui.patron.edit.guardian_required_for_juv',
413             'format.date',
414             'ui.patron.edit.default_suggested',
415             'opac.barcode_regex',
416             'opac.username_regex',
417             'sms.enable',
418             'ui.patron.edit.aua.state.require',
419             'ui.patron.edit.aua.state.suggest',
420             'ui.patron.edit.aua.state.show',
421             'ui.admin.work_log.max_entries',
422             'ui.admin.patron_log.max_entries'
423         ]).then(function(settings) {
424             service.org_settings = settings;
425             if (egCore && egCore.env && !egCore.env.aous) {
426                 egCore.env.aous = settings;
427                 console.log('setting egCore.env.aous');
428             }
429             return service.process_org_settings(settings);
430         });
431     };
432
433     // some org settings require the retrieval of additional data
434     service.process_org_settings = function(settings) {
435
436         var promises = [egLovefield.setSettingsCache(settings)];
437
438         if (settings['sms.enable']) {
439             // fetch SMS carriers
440             promises.push(
441                 egCore.pcrud.search('csc', 
442                     {active: 'true'}, 
443                     {'order_by':[
444                         {'class':'csc', 'field':'name'},
445                         {'class':'csc', 'field':'region'}
446                     ]}, {atomic : true}
447                 ).then(function(carriers) {
448                     service.sms_carriers = carriers;
449                 })
450             );
451         } else {
452             // if other promises are added below, this is not necessary.
453             promises.push($q.when());  
454         }
455
456         // other post-org-settings processing goes here,
457         // adding to promises as needed.
458
459         return $q.all(promises);
460     };
461
462     service.get_ident_types = function() {
463         if (egCore.env.cit) {
464             service.ident_types = egCore.env.cit.list;
465             return $q.when();
466         } else {
467             return egCore.pcrud.retrieveAll('cit', {}, {atomic : true})
468             .then(function(types) { 
469                 egCore.env.absorbList(types, 'cit')
470                 service.ident_types = types 
471             });
472         }
473     };
474
475     service.get_net_access_levels = function() {
476         if (egCore.env.cnal) {
477             service.net_access_levels = egCore.env.cnal.list;
478             return $q.when();
479         } else {
480             return egCore.pcrud.retrieveAll('cnal', {}, {atomic : true})
481             .then(function(levels) { 
482                 egCore.env.absorbList(levels, 'cnal')
483                 service.net_access_levels = levels 
484             });
485         }
486     }
487
488     service.get_perm_groups = function() {
489         if (egCore.env.pgt) {
490             service.profiles = egCore.env.pgt.list;
491             return service.set_edit_profiles();
492         } else {
493             return egCore.pcrud.search('pgt', {parent : null}, 
494                 {flesh : -1, flesh_fields : {pgt : ['children']}}
495             ).then(
496                 function(tree) {
497                     egCore.env.absorbTree(tree, 'pgt')
498                     service.profiles = egCore.env.pgt.list;
499                     return service.set_edit_profiles();
500                 }
501             );
502         }
503     }
504
505     service.searchPermGroupEntries = function(org) {
506         return egCore.pcrud.search('pgtde', {org: org, parent: null},
507             {flesh: -1, flesh_fields: {pgtde: ['grp', 'children']}}, {atomic: true}
508         ).then(function(treeArray) {
509             if (!treeArray.length && egCore.org.get(org).parent_ou()) {
510                 return service.searchPermGroupEntries(egCore.org.get(org).parent_ou());
511             }
512             return treeArray;
513         });
514     }
515
516     service.get_perm_group_entries = function() {
517         if (egCore.env.pgtde) {
518             service.profile_entries = egCore.env.pgtde.list;
519             return service.set_edit_profile_entries();
520         } else {
521             return service.searchPermGroupEntries(egCore.auth.user().ws_ou()).then(function(treeArray) {
522                 function compare(a,b) {
523                   if (a.position() > b.position())
524                     return -1;
525                   if (a.position() < b.position())
526                     return 1;
527                   return 0;
528                 }
529
530                 var list = [];
531                 function squash(node) {
532                     node.children().sort(compare);
533                     list.push(node);
534                     angular.forEach(node.children(), squash);
535                 }
536
537                 angular.forEach(treeArray, squash);
538                 var blob = egCore.env.absorbList(list, 'pgtde');
539                 blob.tree = treeArray;
540
541                 service.profile_entries = egCore.env.pgtde.list;
542                 return service.set_edit_profile_entries();
543             });
544         }
545     }
546
547     service.get_field_doc = function() {
548         var to_cache = [];
549         return egCore.pcrud.search('fdoc', {
550             fm_class: ['au', 'ac', 'aua', 'actsc', 'asv', 'asvq', 'asva']})
551         .then(
552             function () {
553                 return egLovefield.setListInOfflineCache('fdoc', to_cache)
554             },
555             null,
556             function(doc) {
557                 if (!service.field_doc[doc.fm_class()]) {
558                     service.field_doc[doc.fm_class()] = {};
559                 }
560                 service.field_doc[doc.fm_class()][doc.field()] = doc;
561                 to_cache.push(doc);
562             }
563         );
564
565     };
566
567     service.get_user_setting_types = function() {
568
569         // No need to re-fetch the common setting types.
570         if (Object.keys(service.user_setting_types).length) 
571             return $q.when();
572
573         var org_ids = egCore.org.ancestors(egCore.auth.user().ws_ou(), true);
574
575         var static_types = [
576             'circ.holds_behind_desk', 
577             'circ.collections.exempt', 
578             'opac.hold_notify', 
579             'opac.default_phone', 
580             'opac.default_pickup_location', 
581             'opac.default_sms_carrier', 
582             'opac.default_sms_notify'];
583
584         return egCore.pcrud.search('cust', {
585             '-or' : [
586                 {name : static_types}, // common user settings
587                 {name : { // opt-in notification user settings
588                     'in': {
589                         select : {atevdef : ['opt_in_setting']}, 
590                         from : 'atevdef',
591                         // we only care about opt-in settings for 
592                         // event_defs our users encounter
593                         where : {'+atevdef' : {owner : org_ids}}
594                     }
595                 }}
596             ]
597         }, {}, {atomic : true}).then(function(setting_types) {
598
599             egCore.env.absorbList(setting_types, 'cust'); // why not...
600
601             angular.forEach(setting_types, function(stype) {
602                 service.user_setting_types[stype.name()] = stype;
603                 if (static_types.indexOf(stype.name()) == -1) {
604                     service.opt_in_setting_types[stype.name()] = stype;
605                 }
606             });
607         });
608     };
609
610     service.get_user_settings = function() {
611
612         return service.get_user_setting_types()
613         .then(function() {
614
615             var setting_types = Object.values(service.user_setting_types);
616
617             if (service.patron_id) {
618                 // retrieve applied values for the current user 
619                 // for the setting types we care about.
620
621                 var setting_names = 
622                     setting_types.map(function(obj) { return obj.name() });
623
624                 return egCore.net.request(
625                     'open-ils.actor', 
626                     'open-ils.actor.patron.settings.retrieve.authoritative',
627                     egCore.auth.token(),
628                     service.patron_id,
629                     setting_names
630                 ).then(function(settings) {
631                     service.user_settings = settings;
632                 });
633
634             } else {
635
636                 // apply default user setting values
637                 angular.forEach(setting_types, function(stype, index) {
638                     if (stype.reg_default() != undefined) {
639                         var val = stype.reg_default();
640                         if (stype.datatype() == 'bool') {
641                             // A boolean user setting type whose default 
642                             // value starts with t/T is considered 'true',
643                             // false otherwise.
644                             val = Boolean((val+'').match(/^t/i));
645                         }
646                         service.user_settings[stype.name()] = val;
647                     }
648                 });
649             }
650         });
651     }
652
653     service.invalidate_field = function(patron, field) {
654         console.log('Invalidating patron field ' + field);
655
656         return egCore.net.request(
657             'open-ils.actor',
658             'open-ils.actor.invalidate.' + field,
659             egCore.auth.token(), patron.id, null, patron.home_ou.id()
660
661         ).then(function(res) {
662             // clear the invalid value from the form
663             patron[field] = '';
664
665             // update last_xact_id so future save operations
666             // on this patron will be allowed
667             patron.last_xact_id = res.payload.last_xact_id[patron.id];
668         });
669     }
670
671     service.send_test_message = function(user_id, hook) {
672
673         return egCore.net.request(
674             'open-ils.actor',
675             'open-ils.actor.event.test_notification',
676             egCore.auth.token(), {hook: hook, target: user_id}
677         ).then(function(res) {
678             return res;
679         });
680     }
681
682     service.dupe_patron_search = function(patron, type, value) {
683         var search;
684
685         console.log('Dupe search called with "'+ type +'" and value '+ value);
686
687         if (type.match(/phone/)) type = 'phone'; // day_phone, etc.
688
689         switch (type) {
690
691             case 'name':
692                 var fname = patron.first_given_name;   
693                 var lname = patron.family_name;   
694                 if (!(fname && lname)) return $q.when({count:0});
695                 search = {
696                     first_given_name : {value : fname, group : 0},
697                     family_name : {value : lname, group : 0}
698                 };
699                 break;
700
701             case 'email':
702                 search = {email : {value : value, group : 0}};
703                 break;
704
705             case 'ident':
706                 search = {ident : {value : value, group : 2}};
707                 break;
708
709             case 'phone':
710                 search = {phone : {value : value, group : 2}};
711                 break;
712
713             case 'address':
714                 search = {};
715                 angular.forEach(['street1', 'street2', 'city', 'post_code'],
716                     function(field) {
717                         if(value[field])
718                             search[field] = {value : value[field], group: 1};
719                     }
720                 );
721                 break;
722         }
723
724         return egCore.net.request( 
725             'open-ils.actor', 
726             'open-ils.actor.patron.search.advanced',
727             egCore.auth.token(), search, null, null, 1
728         ).then(function(res) {
729             res = res.filter(function(id) {return id != patron.id});
730             return {
731                 count : res.length,
732                 search : search
733             };
734         });
735     }
736
737     service.init_patron = function(current) {
738
739         if (!current)
740             return $q.when(service.init_new_patron());
741
742         service.patron = current;
743         return $q.when(service.init_existing_patron(current));
744     }
745
746     service.ingest_address = function(patron, addr) {
747         addr.valid = addr.valid == 't';
748         addr.within_city_limits = addr.within_city_limits == 't';
749         addr._is_mailing = (patron.mailing_address && 
750             addr.id == patron.mailing_address.id);
751         addr._is_billing = (patron.billing_address && 
752             addr.id == patron.billing_address.id);
753         addr.pending = addr.pending === 't';
754     }
755
756     service.ingest_waiver_entry = function(patron, waiver_entry) {
757         waiver_entry.place_holds = waiver_entry.place_holds == 't';
758         waiver_entry.pickup_holds = waiver_entry.pickup_holds == 't';
759         waiver_entry.view_history = waiver_entry.view_history == 't';
760         waiver_entry.checkout_items = waiver_entry.checkout_items == 't';
761     }
762
763     /*
764      * Existing patron objects reqire some data munging before insertion
765      * into the scope.
766      *
767      * 1. Turn everything into a hash
768      * 2. ... Except certain fields (selectors) whose widgets require objects
769      * 3. Bools must be Boolean, not t/f.
770      */
771     service.init_existing_patron = function(current) {
772
773         service.existing_patron = current;
774
775         var patron = egCore.idl.toHash(current);
776
777         patron.home_ou = egCore.org.get(patron.home_ou.id);
778         patron.expire_date = new Date(Date.parse(patron.expire_date));
779         patron.dob = service.parse_dob(patron.dob);
780         patron.profile = current.profile(); // pre-hash version
781         patron.net_access_level = current.net_access_level();
782         patron.ident_type = current.ident_type();
783         patron.ident_type2 = current.ident_type2();
784         patron.groups = current.groups(); // pre-hash
785
786         angular.forEach(
787             ['juvenile', 'barred', 'active', 'master_account'],
788             function(field) { patron[field] = patron[field] == 't'; }
789         );
790
791         angular.forEach(patron.cards, function(card) {
792             card.active = card.active == 't';
793             if (card.id == patron.card.id) {
794                 patron.card = card;
795                 card._primary = true;
796             }
797         });
798
799         angular.forEach(patron.addresses, 
800             function(addr) { service.ingest_address(patron, addr) });
801
802         // Link replaced address to its pending address.
803         angular.forEach(patron.addresses, function(addr) {
804             if (addr.replaces) {
805                 addr._replaces = patron.addresses.filter(
806                     function(a) {return a.id == addr.replaces})[0];
807             }
808         });
809
810         angular.forEach(patron.waiver_entries,
811             function(waiver_entry) { service.ingest_waiver_entry(patron, waiver_entry) });
812
813         service.get_linked_addr_users(patron.addresses);
814
815         // Remove stat cat entries that link to out-of-scope stat
816         // cats.  With this, we avoid unnecessarily updating (or worse,
817         // modifying) stat cat values that are not ours to modify.
818         patron.stat_cat_entries = patron.stat_cat_entries.filter(
819             function(map) {
820                 return Boolean(
821                     // service.stat_cats only contains in-scope stat cats.
822                     service.stat_cats.filter(function(cat) { 
823                         return (cat.id() == map.stat_cat.id) })[0]
824                 );
825             }
826         );
827
828         // toss entries for existing stat cat maps into our living 
829         // stat cat entry map, which is modified within the template.
830         service.stat_cat_entry_maps = [];
831         angular.forEach(patron.stat_cat_entries, function(map) {
832             service.stat_cat_entry_maps[map.stat_cat.id] = map.stat_cat_entry;
833         });
834
835         service.patron = patron;
836         return patron;
837     }
838
839     service.init_new_patron = function() {
840         var addr = {
841             id : service.virt_id--,
842             isnew : true,
843             valid : true,
844             address_type : egCore.strings.REG_ADDR_TYPE,
845             _is_mailing : true,
846             _is_billing : true,
847             within_city_limits : false,
848             country : service.org_settings['ui.patron.default_country'],
849         };
850
851         var card = {
852             id : service.virt_id--,
853             isnew : true,
854             active : true,
855             _primary : true
856         };
857
858         var user = {
859             isnew : true,
860             active : true,
861             card : card,
862             cards : [card],
863             home_ou : egCore.org.get(egCore.auth.user().ws_ou()),
864             stat_cat_entries : [],
865             waiver_entries : [],
866             groups : [],
867             addresses : [addr]
868         };
869
870         if (service.clone_user)
871             service.copy_clone_data(user);
872
873         if (service.stage_user)
874             service.copy_stage_data(user);
875
876         return user;
877     }
878
879     // dob is always YYYY-MM-DD
880     // Dates of birth do not contain timezone info, which can lead to
881     // inconcistent timezone handling, potentially representing
882     // different points in time, depending on the implementation.
883     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
884     // See "Differences in assumed time zone"
885     // TODO: move this into egDate ?
886     service.parse_dob = function(dob) {
887         if (!dob) return null;
888         var parts = dob.split('-');
889         return new Date(parts[0], parts[1] - 1, parts[2])
890     }
891
892     service.copy_stage_data = function(user) {
893         var cuser = service.stage_user;
894
895         // copy the data into our new user object
896
897         for (var key in egCore.idl.classes.stgu.field_map) {
898             if (egCore.idl.classes.au.field_map[key] &&
899                 !egCore.idl.classes.stgu.field_map[key].virtual) {
900                 if (cuser.user[key]() !== null)
901                     user[key] = cuser.user[key]();
902             }
903         }
904
905         if (user.home_ou) user.home_ou = egCore.org.get(user.home_ou);
906         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
907         if (user.ident_type) 
908             user.ident_type = egCore.env.cit.map[user.ident_type];
909         if (user.ident_type2)
910             user.ident_type2 = egCore.env.cit.map[user.ident_type2];
911         user.dob = service.parse_dob(user.dob);
912
913         // Clear the usrname if it looks like a UUID
914         if (user.usrname.replace(/-/g,'').match(/[0-9a-f]{32}/)) 
915             user.usrname = '';
916
917         // Don't use stub address if we have one from the staged user.
918         if (cuser.mailing_addresses.length || cuser.billing_addresses.length)
919             user.addresses = [];
920
921         // is_mailing=false implies is_billing
922         function addr_from_stage(stage_addr) {
923             if (!stage_addr) return;
924             var cls = stage_addr.classname;
925
926             var addr = {
927                 id : service.virt_id--,
928                 usr : user.id,
929                 isnew : true,
930                 valid : true,
931                 address_type : egCore.strings.REG_ADDR_TYPE,
932                 _is_mailing : cls == 'stgma',
933                 _is_billing : cls == 'stgba'
934             };
935
936             user.mailing_address = addr;
937             user.addresses.push(addr);
938
939             for (var key in egCore.idl.classes[cls].field_map) {
940                 if (egCore.idl.classes.aua.field_map[key] &&
941                     !egCore.idl.classes[cls].field_map[key].virtual) {
942                     if (stage_addr[key]() !== null)
943                         addr[key] = stage_addr[key]();
944                 }
945             }
946         }
947
948         addr_from_stage(cuser.mailing_addresses[0]);
949         addr_from_stage(cuser.billing_addresses[0]);
950
951         if (user.addresses.length == 1) {
952             // If there is only one address, 
953             // use it as both mailing and billing.
954             var addr = user.addresses[0];
955             addr._is_mailing = addr._is_billing = true;
956             user.mailing_address = user.billing_address = addr;
957         }
958
959         if (cuser.cards.length) {
960             user.card = {
961                 id : service.virt_id--,
962                 barcode : cuser.cards[0].barcode(),
963                 isnew : true,
964                 active : true,
965                 _primary : true
966             };
967
968             user.cards.push(user.card);
969             if (user.usrname == '') 
970                 user.usrname = card.barcode;
971         }
972
973         angular.forEach(cuser.settings, function(setting) {
974             service.user_settings[setting.setting()] = Boolean(setting.value());
975         });
976     }
977
978     // copy select values from the cloned user to the new user.
979     // user is a hash
980     service.copy_clone_data = function(user) {
981         var clone_user = service.clone_user;
982
983         // flesh the home org locally
984         user.home_ou = egCore.org.get(clone_user.home_ou());
985         if (user.profile) user.profile = egCore.env.pgt.map[user.profile];
986
987         if (!clone_user.billing_address() &&
988             !clone_user.mailing_address())
989             return; // no addresses to copy or link
990
991         // if the cloned user has any addresses, we don't need 
992         // the stub address created in init_new_patron.
993         user.addresses = [];
994
995         var copy_addresses = 
996             service.org_settings['circ.patron_edit.clone.copy_address'];
997
998         var clone_fields = [
999             'day_phone',
1000             'evening_phone',
1001             'other_phone',
1002             'usrgroup'
1003         ]; 
1004
1005         angular.forEach(clone_fields, function(field) {
1006             user[field] = clone_user[field]();
1007         });
1008
1009         if (copy_addresses) {
1010             var bill_addr, mail_addr;
1011
1012             // copy the billing and mailing addresses into new addresses
1013             function clone_addr(addr) {
1014                 var new_addr = egCore.idl.toHash(addr);
1015                 new_addr.id = service.virt_id--;
1016                 new_addr.usr = user.id;
1017                 new_addr.isnew = true;
1018                 new_addr.valid = true;
1019                 user.addresses.push(new_addr);
1020                 return new_addr;
1021             }
1022
1023             if (bill_addr = clone_user.billing_address()) {
1024                 var addr = clone_addr(bill_addr);
1025                 addr._is_billing = true;
1026                 user.billing_address = addr;
1027             }
1028
1029             if (mail_addr = clone_user.mailing_address()) {
1030
1031                 if (bill_addr && bill_addr.id() == mail_addr.id()) {
1032                     user.mailing_address = user.billing_address;
1033                     user.mailing_address._is_mailing = true;
1034                 } else {
1035                     var addr = clone_addr(mail_addr);
1036                     addr._is_mailing = true;
1037                     user.mailing_address = addr;
1038                 }
1039
1040                 if (!bill_addr) {
1041                     // if there is no billing addr, use the mailing addr
1042                     user.billing_address = user.mailing_address;
1043                     user.billing_address._is_billing = true;
1044                 }
1045             }
1046
1047
1048         } else {
1049
1050             // link the billing and mailing addresses
1051             var addr;
1052             if (addr = clone_user.billing_address()) {
1053                 user.billing_address = egCore.idl.toHash(addr);
1054                 user.billing_address._is_billing = true;
1055                 user.addresses.push(user.billing_address);
1056                 user.billing_address._linked_owner_id = clone_user.id();
1057                 user.billing_address._linked_owner = service.format_name(
1058                     clone_user.family_name(),
1059                     clone_user.first_given_name(),
1060                     clone_user.second_given_name()
1061                 );
1062             }
1063
1064             if (addr = clone_user.mailing_address()) {
1065                 if (user.billing_address && 
1066                     addr.id() == user.billing_address.id) {
1067                     // mailing matches billing
1068                     user.mailing_address = user.billing_address;
1069                     user.mailing_address._is_mailing = true;
1070                 } else {
1071                     user.mailing_address = egCore.idl.toHash(addr);
1072                     user.mailing_address._is_mailing = true;
1073                     user.addresses.push(user.mailing_address);
1074                     user.mailing_address._linked_owner_id = clone_user.id();
1075                     user.mailing_address._linked_owner = service.format_name(
1076                         clone_user.family_name(),
1077                         clone_user.first_given_name(),
1078                         clone_user.second_given_name()
1079                     );
1080                 }
1081             }
1082         }
1083     }
1084
1085     // translate the patron back into IDL form
1086     service.save_user = function(phash) {
1087
1088         var patron = egCore.idl.fromHash('au', phash);
1089
1090         patron.home_ou(patron.home_ou().id());
1091         patron.expire_date(patron.expire_date().toISOString());
1092         patron.profile(patron.profile().id());
1093         if (patron.dob()) 
1094             patron.dob(patron.dob().toISOString().replace(/T.*/,''));
1095         if (patron.ident_type()) 
1096             patron.ident_type(patron.ident_type().id());
1097         if (patron.net_access_level())
1098             patron.net_access_level(patron.net_access_level().id());
1099
1100         angular.forEach(
1101             ['juvenile', 'barred', 'active', 'master_account'],
1102             function(field) { patron[field](phash[field] ? 't' : 'f'); }
1103         );
1104
1105         var card_hashes = patron.cards();
1106         patron.cards([]);
1107         angular.forEach(card_hashes, function(chash) {
1108             var card = egCore.idl.fromHash('ac', chash)
1109             card.usr(patron.id());
1110             card.active(chash.active ? 't' : 'f');
1111             patron.cards().push(card);
1112             if (chash._primary) {
1113                 patron.card(card);
1114             }
1115         });
1116
1117         var addr_hashes = patron.addresses();
1118         patron.addresses([]);
1119         angular.forEach(addr_hashes, function(addr_hash) {
1120             if (!addr_hash.isnew && !addr_hash.isdeleted) 
1121                 addr_hash.ischanged = true;
1122             var addr = egCore.idl.fromHash('aua', addr_hash);
1123             patron.addresses().push(addr);
1124             addr.valid(addr.valid() ? 't' : 'f');
1125             addr.within_city_limits(addr.within_city_limits() ? 't' : 'f');
1126             addr.pending(addr.pending() ? 't' : 'f');
1127             if (addr_hash._is_mailing) patron.mailing_address(addr);
1128             if (addr_hash._is_billing) patron.billing_address(addr);
1129         });
1130
1131         patron.survey_responses([]);
1132         angular.forEach(service.survey_responses, function(answer) {
1133             var question = service.survey_questions[answer.question()];
1134             var resp = new egCore.idl.asvr();
1135             resp.isnew(true);
1136             resp.survey(question.survey());
1137             resp.question(question.id());
1138             resp.answer(answer.id());
1139             resp.usr(patron.id());
1140             resp.answer_date('now');
1141             patron.survey_responses().push(resp);
1142         });
1143         
1144         // re-object-ify the patron stat cat entry maps
1145         var maps = [];
1146         angular.forEach(patron.stat_cat_entries(), function(entry) {
1147             var e = egCore.idl.fromHash('actscecm', entry);
1148             e.stat_cat(e.stat_cat().id);
1149             maps.push(e);
1150         });
1151         patron.stat_cat_entries(maps);
1152
1153         // service.stat_cat_entry_maps maps stats to values
1154         // patron.stat_cat_entries is an array of stat_cat_entry_usr_map's
1155         angular.forEach(
1156             service.stat_cat_entry_maps, function(value, cat_id) {
1157
1158             // see if we already have a mapping for this entry
1159             var existing = patron.stat_cat_entries().filter(
1160                 function(e) { return e.stat_cat() == cat_id })[0];
1161
1162             if (existing) { // we have a mapping
1163                 // if the existing mapping matches the new one,
1164                 // there' nothing left to do
1165                 if (existing.stat_cat_entry() == value) return;
1166
1167                 // mappings differ.  delete the old one and create
1168                 // a new one below.
1169                 existing.isdeleted(true);
1170             }
1171
1172             var newmap = new egCore.idl.actscecm();
1173             newmap.target_usr(patron.id());
1174             newmap.isnew(true);
1175             newmap.stat_cat(cat_id);
1176             newmap.stat_cat_entry(value);
1177             patron.stat_cat_entries().push(newmap);
1178         });
1179
1180         var waiver_hashes = patron.waiver_entries();
1181         patron.waiver_entries([]);
1182         angular.forEach(waiver_hashes, function(waiver_hash) {
1183             if (!waiver_hash.isnew && !waiver_hash.isdeleted)
1184                 waiver_hash.ischanged = true;
1185             var waiver_entry = egCore.idl.fromHash('aupw', waiver_hash);
1186             patron.waiver_entries().push(waiver_entry);
1187         });
1188
1189         if (!patron.isnew()) patron.ischanged(true);
1190
1191         return egCore.net.request(
1192             'open-ils.actor', 
1193             'open-ils.actor.patron.update',
1194             egCore.auth.token(), patron);
1195     }
1196
1197     service.remove_staged_user = function() {
1198         if (!service.stage_user) return $q.when();
1199         return egCore.net.request(
1200             'open-ils.actor',
1201             'open-ils.actor.user.stage.delete',
1202             egCore.auth.token(),
1203             service.stage_user.user.row_id()
1204         );
1205     }
1206
1207     service.save_user_settings = function(new_user, user_settings) {
1208
1209         var settings = {};
1210         if (service.patron_id) {
1211             // Update all user editor setting values for existing 
1212             // users regardless of whether a value changed.
1213             settings = user_settings;
1214
1215         } else {
1216             // Create settings for all non-null setting values for new patrons.
1217             angular.forEach(user_settings, function(val, key) {
1218                 if (val !== null) settings[key] = val;
1219             });
1220         }
1221
1222         if (Object.keys(settings).length == 0) return $q.when();
1223
1224         return egCore.net.request(
1225             'open-ils.actor',
1226             'open-ils.actor.patron.settings.update',
1227             egCore.auth.token(), new_user.id(), settings
1228         ).then(function(resp) {
1229             return resp;
1230         });
1231     }
1232
1233     // Applies field-specific validation regex's from org settings 
1234     // to form fields.  Be careful not remove any pattern data we
1235     // are not explicitly over-writing in the provided patterns obj.
1236     service.set_field_patterns = function(patterns) {
1237         if (service.org_settings['opac.username_regex']) {
1238             patterns.au.usrname = 
1239                 new RegExp(service.org_settings['opac.username_regex']);
1240         }
1241
1242         if (service.org_settings['ui.patron.edit.ac.barcode.regex']) {
1243             patterns.ac.barcode = 
1244                 new RegExp(service.org_settings['ui.patron.edit.ac.barcode.regex']);
1245         }
1246
1247         if (service.org_settings['global.password_regex']) {
1248             patterns.au.passwd = 
1249                 new RegExp(service.org_settings['global.password_regex']);
1250         }
1251
1252         var phone_reg = service.org_settings['ui.patron.edit.phone.regex'];
1253         if (phone_reg) {
1254             // apply generic phone regex first, replace below as needed.
1255             patterns.au.day_phone = new RegExp(phone_reg);
1256             patterns.au.evening_phone = new RegExp(phone_reg);
1257             patterns.au.other_phone = new RegExp(phone_reg);
1258         }
1259
1260         // the remaining patterns fit a well-known key name pattern
1261
1262         angular.forEach(service.org_settings, function(val, key) {
1263             if (!val) return;
1264             var parts = key.match(/ui.patron.edit\.(\w+)\.(\w+)\.regex/);
1265             if (!parts) return;
1266             var cls = parts[1];
1267             var name = parts[2];
1268             patterns[cls][name] = new RegExp(val);
1269         });
1270     }
1271
1272     return service;
1273 }])
1274
1275 .controller('PatronRegCtrl',
1276        ['$scope','$routeParams','$q','$uibModal','$window','egCore',
1277         'patronSvc','patronRegSvc','egUnloadPrompt','egAlertDialog',
1278         'egWorkLog', '$timeout', 'ngToast',
1279 function($scope , $routeParams , $q , $uibModal , $window , egCore ,
1280          patronSvc , patronRegSvc , egUnloadPrompt, egAlertDialog ,
1281          egWorkLog, $timeout, ngToast) {
1282
1283     $scope.page_data_loaded = false;
1284     $scope.hold_notify_type = { phone : null, email : null, sms : null };
1285     $scope.hold_notify_observer = {};
1286     $scope.hold_rel_contacts = {};
1287     $scope.clone_id = patronRegSvc.clone_id = $routeParams.clone_id;
1288     $scope.stage_username = 
1289         patronRegSvc.stage_username = $routeParams.stage_username;
1290     $scope.patron_id = 
1291         patronRegSvc.patron_id = $routeParams.edit_id || $routeParams.id;
1292
1293     // for existing patrons, disable barcode input by default
1294     $scope.disable_bc = $scope.focus_usrname = Boolean($scope.patron_id);
1295     $scope.focus_bc = !Boolean($scope.patron_id);
1296     $scope.address_alerts = [];
1297     $scope.dupe_counts = {};
1298
1299     // map of perm name to true/false for perms the logged in user
1300     // has at the currently selected patron home org unit.
1301     $scope.perms = {};
1302
1303     $scope.name_tab = 'primary';
1304
1305     if (!$scope.edit_passthru) {
1306         // in edit more, scope.edit_passthru is delivered to us by
1307         // the enclosing controller.  In register mode, there is 
1308         // no enclosing controller, so we create our own.
1309         $scope.edit_passthru = {};
1310     }
1311
1312     // 0=all, 1=suggested, 2=all
1313     $scope.edit_passthru.vis_level = 0; 
1314
1315     // Apply default values for new patrons during initial registration
1316     // prs is shorthand for patronSvc
1317     function set_new_patron_defaults(prs) {
1318         if (!$scope.patron.passwd) {
1319             // passsword may originate from staged user.
1320             if ($scope.patron.day_phone &&
1321                 $scope.org_settings['patron.password.use_phone']) {
1322                 $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
1323             } else {
1324                 $scope.generate_password();
1325             }
1326         }
1327
1328         var notify = 'phone:email'; // hard-coded default when opac.hold_notify has no reg_default
1329         var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1330         if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1331             console.log('using default opac.hold_notify');
1332             notify = notify_stype.reg_default();
1333         }
1334         $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1335         $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1336         $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1337
1338         // staged users may be loaded w/ a profile.
1339         $scope.set_expire_date();
1340
1341         if (prs.org_settings['ui.patron.default_ident_type']) {
1342             // $scope.patron needs this field to be an object
1343             var id = prs.org_settings['ui.patron.default_ident_type'];
1344             var ident_type = $scope.ident_types.filter(
1345                 function(type) { return type.id() == id })[0];
1346             $scope.patron.ident_type = ident_type;
1347         }
1348         if (prs.org_settings['ui.patron.default_inet_access_level']) {
1349             // $scope.patron needs this field to be an object
1350             var id = prs.org_settings['ui.patron.default_inet_access_level'];
1351             var level = $scope.net_access_levels.filter(
1352                 function(lvl) { return lvl.id() == id })[0];
1353             $scope.patron.net_access_level = level;
1354         }
1355         if (prs.org_settings['ui.patron.default_country']) {
1356             $scope.patron.addresses[0].country = 
1357                 prs.org_settings['ui.patron.default_country'];
1358         }
1359     }
1360
1361     // A null or undefined pattern leads to exceptions.  Before the
1362     // patterns are loaded from the server, default all patterns
1363     // to an innocuous regex.  To avoid re-creating numerous
1364     // RegExp objects, cache the stub RegExp after initial creation.
1365     // note: angular docs say ng-pattern accepts a regexp or string,
1366     // but as of writing, it only works with a regexp object.
1367     // (Likely an angular 1.2 vs. 1.4 issue).
1368     var field_patterns = {au : {}, ac : {}, aua : {}};
1369     $scope.field_pattern = function(cls, field) { 
1370         if (!field_patterns[cls][field])
1371             field_patterns[cls][field] = new RegExp('.*');
1372         return field_patterns[cls][field];
1373     }
1374
1375     // Main page load function.  Kicks off tab init and data loading.
1376     $q.all([
1377
1378         $scope.initTab ? // initTab comes from patron app
1379             $scope.initTab('edit', $routeParams.id) : $q.when(),
1380
1381         patronRegSvc.init(),
1382
1383     ]).then(function(){ return patronRegSvc.init_patron(patronSvc ? patronSvc.current : patronRegSvc.patron ) })
1384       .then(function(patron) {
1385         // called after initTab and patronRegSvc.init have completed
1386         // in standalone mode, we have no patronSvc
1387         var prs = patronRegSvc;
1388         $scope.patron = patron;
1389         $scope.base_email = patron.email;
1390         $scope.base_default_sms = prs.user_settings['opac.default_sms_notify']
1391         $scope.field_doc = prs.field_doc;
1392         $scope.edit_profiles = prs.edit_profiles;
1393         $scope.edit_profile_entries = prs.edit_profile_entries;
1394         $scope.ident_types = prs.ident_types;
1395         $scope.net_access_levels = prs.net_access_levels;
1396         $scope.user_setting_types = prs.user_setting_types;
1397         $scope.opt_in_setting_types = prs.opt_in_setting_types;
1398         $scope.org_settings = prs.org_settings;
1399         $scope.sms_carriers = prs.sms_carriers;
1400         $scope.stat_cats = prs.stat_cats;
1401         $scope.surveys = prs.surveys;
1402         $scope.survey_responses = prs.survey_responses;
1403         $scope.stat_cat_entry_maps = prs.stat_cat_entry_maps;
1404         $scope.stage_user = prs.stage_user;
1405         $scope.stage_user_requestor = prs.stage_user_requestor;
1406
1407         $scope.user_settings = prs.user_settings;
1408         prs.user_settings = {};
1409
1410         // If a default pickup lib is applied to the patron, apply it 
1411         // to the UI at page load time.  Otherwise, leave the value unset.
1412         if ($scope.user_settings['opac.default_pickup_location']) {
1413             $scope.patron._pickup_lib = egCore.org.get(
1414                 $scope.user_settings['opac.default_pickup_location']);
1415         }
1416
1417         extract_hold_notify();
1418
1419         if ($scope.patron.isnew)
1420             set_new_patron_defaults(prs);
1421
1422         $scope.handle_home_org_changed();
1423
1424         if ($scope.org_settings['ui.patron.edit.default_suggested'])
1425             $scope.edit_passthru.vis_level = 1;
1426
1427         // Stat cats are fetched from open-ils.storage, where 't'==1
1428         $scope.hasRequiredStatCat = prs.stat_cats.filter(
1429                 function(cat) {return cat.required() == 1} ).length > 0;
1430
1431         $scope.page_data_loaded = true;
1432
1433         prs.set_field_patterns(field_patterns);
1434         apply_username_regex();
1435
1436         add_date_watchers();
1437
1438         if ($scope.org_settings['ui.patron.edit.guardian_required_for_juv']) {
1439             add_juv_watcher();
1440         }
1441     });
1442
1443     function add_date_watchers() {
1444
1445         $scope.$watch('patron.dob', function(newVal, oldVal) {
1446             // Even though this runs after page data load, there
1447             // are still times when it fires unnecessarily.
1448             if (newVal === oldVal) return;
1449
1450             console.debug('dob change: ' + newVal + ' : ' + oldVal);
1451             maintain_juvenile_flag();
1452         });
1453
1454         // No need to watch expire_date
1455     }
1456
1457     function add_juv_watcher() {
1458         $scope.$watch('patron.juvenile', function(newVal, oldVal) {
1459             if (newVal === oldVal) return;
1460             if (newVal) {
1461                 field_visibility['au.guardian'] = 3; // required
1462             } else {
1463                 // Value will be reassessed by show_field()
1464                 delete field_visibility['au.guardian'];
1465             }
1466         });
1467     }
1468     
1469     // add watchers for hold notify method prefs
1470     $scope.$watch('hold_notify_type.phone', function(newVal, oldVal) {
1471         var notifyOpt = $scope.hold_notify_observer['phone'];
1472         if (newVal !== null) {
1473             notifyOpt.newval = newVal;
1474         }
1475     });
1476
1477     $scope.$watch('hold_notify_type.sms', function(newVal, oldVal) {
1478         var notifyOpt = $scope.hold_notify_observer['sms'];
1479         if (newVal !== null) {
1480             notifyOpt.newval = newVal;
1481         }
1482     });
1483     
1484     $scope.$watch('hold_notify_type.email', function(newVal, oldVal) {
1485         var notifyOpt = $scope.hold_notify_observer['email'];
1486         if (newVal !== null) {
1487             notifyOpt.newval = newVal;
1488         }
1489     });
1490
1491     // update the currently displayed field documentation
1492     $scope.set_selected_field_doc = function(cls, field) {
1493         $scope.selected_field_doc = $scope.field_doc[cls][field];
1494     }
1495
1496     // returns the tree depth of the selected profile group tree node.
1497     $scope.pgt_depth = function(grp) {
1498         var d = 0;
1499         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1500         return d;
1501     }
1502
1503     // returns the tree depth of the selected profile group tree node.
1504     $scope.pgtde_depth = function(entry) {
1505         var d = 0;
1506         while (entry = egCore.env.pgtde.map[entry.parent()]) d++;
1507         return d;
1508     }
1509
1510     // IDL fields used for labels in the UI.
1511     $scope.idl_fields = {
1512         au  : egCore.idl.classes.au.field_map,
1513         ac  : egCore.idl.classes.ac.field_map,
1514         aua : egCore.idl.classes.aua.field_map
1515     };
1516
1517     // field visibility cache.  Some fields are universally required.
1518     // 3 == value universally required
1519     // 2 == field is visible by default
1520     // 1 == field is suggested by default
1521     var field_visibility = {};
1522     var default_field_visibility = {
1523         'ac.barcode' : 3,
1524         'au.usrname' : 3,
1525         'au.passwd' :  3,
1526         'au.first_given_name' : 3,
1527         'au.family_name' : 3,
1528         'au.pref_first_given_name' : 2,
1529         'au.pref_family_name' : 2,
1530         'au.ident_type' : 3,
1531         'au.ident_type2' : 2,
1532         'au.photo_url' : 2,
1533         'au.home_ou' : 3,
1534         'au.profile' : 3,
1535         'au.expire_date' : 3,
1536         'au.net_access_level' : 3,
1537         'aua.address_type' : 3,
1538         'aua.post_code' : 3,
1539         'aua.street1' : 3,
1540         'aua.street2' : 2,
1541         'aua.city' : 3,
1542         'aua.county' : 2,
1543         'aua.state' : 2,
1544         'aua.country' : 3,
1545         'aua.valid' : 2,
1546         'aua.within_city_limits' : 2,
1547         'stat_cats' : 1,
1548         'surveys' : 1,
1549         'au.name_keywords': 1
1550     }; 
1551
1552     // Returns true if the selected field should be visible
1553     // given the current required/suggested/all setting.
1554     // The visibility flag applied to each field as a result of calling
1555     // this function also sets (via the same flag) the requiredness state.
1556     $scope.show_field = function(field_key) {
1557         // org settings have not been received yet.
1558         if (!$scope.org_settings) return false;
1559
1560         if (field_visibility[field_key] == undefined) {
1561             // compile and cache the visibility for the selected field
1562
1563             // The preferred name fields use the primary name field settings
1564             var org_key = field_key;
1565             var alt_name = false;
1566             if (field_key.match(/^au.alt_/)) {
1567                 alt_name = true;
1568                 org_key = field_key.slice(7);
1569             }
1570
1571             var req_set = 'ui.patron.edit.' + org_key + '.require';
1572             var sho_set = 'ui.patron.edit.' + org_key + '.show';
1573             var sug_set = 'ui.patron.edit.' + org_key + '.suggest';
1574
1575             if ($scope.org_settings[req_set]) {
1576                 if (alt_name) {
1577                     // Avoid requiring alt name fields when primary 
1578                     // name fields are required.
1579                     field_visibility[field_key] = 2;
1580                 } else {
1581                     field_visibility[field_key] = 3;
1582                 }
1583
1584             } else if ($scope.org_settings[sho_set]) {
1585                 field_visibility[field_key] = 2;
1586
1587             } else if ($scope.org_settings[sug_set]) {
1588                 field_visibility[field_key] = 1;
1589             }
1590         }
1591
1592         if (field_visibility[field_key] == undefined) {
1593             // No org settings were applied above.  Use the default
1594             // settings if present or assume the field has no
1595             // visibility flags applied.
1596             field_visibility[field_key] = 
1597                 default_field_visibility[field_key] || 0;
1598         }
1599
1600         return field_visibility[field_key] >= $scope.edit_passthru.vis_level;
1601     }
1602
1603     // See $scope.show_field().
1604     // A field with visbility level 3 means it's required.
1605     $scope.field_required = function(cls, field) {
1606
1607         // Value in the password field is not required
1608         // for existing patrons.
1609         if (field == 'passwd' && $scope.patron && !$scope.patron.isnew) 
1610           return false;
1611
1612         return (field_visibility[cls + '.' + field] == 3);
1613     }
1614
1615     // generates a random 4-digit password
1616     $scope.generate_password = function() {
1617         $scope.patron.passwd = Math.floor(Math.random()*9000) + 1000;
1618     }
1619
1620     $scope.send_password_reset_link = function() {
1621        if (!$scope.patron.email || $scope.patron.email == '') {
1622             egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_NO_EMAIL);
1623             return;
1624         } else if (patronRegSvc.check_email_different($scope.patron.email)) {
1625             egAlertDialog.open(egCore.strings.REG_PASSWORD_RESET_REQUEST_DIFFERENT_EMAIL);
1626             return;
1627         }
1628         // we have an email address, fire the reset request
1629         egCore.net.request(
1630             'open-ils.actor',
1631             'open-ils.actor.patron.password_reset.request',
1632             'barcode', $scope.patron.card.barcode, $scope.patron.email
1633         ).then(function(resp) {
1634             if (resp == '1') { // request okay
1635                 ngToast.success(egCore.strings.REG_PASSWORD_RESET_REQUEST_SUCCESSFUL);
1636             } else {
1637                 var evt = egCore.evt.parse(resp);
1638                 egAlertDialog.open(evt.desc);
1639             }
1640         });
1641     }
1642
1643     $scope.set_expire_date = function() {
1644         if (!$scope.patron.profile) return;
1645         var seconds = egCore.date.intervalToSeconds(
1646             $scope.patron.profile.perm_interval());
1647         var now_epoch = new Date().getTime();
1648         $scope.patron.expire_date = new Date(
1649             now_epoch + (seconds * 1000 /* milliseconds */))
1650         $scope.field_modified();
1651     }
1652
1653     // grp is the pgt object
1654     $scope.set_profile = function(grp) {
1655         // If we can't save because of group perms or create/update perms
1656         if ($scope.edit_passthru.hide_save_actions()) return;
1657         $scope.patron.profile = grp;
1658         $scope.set_expire_date();
1659         $scope.field_modified();
1660     }
1661
1662     $scope.invalid_profile = function() {
1663         return !(
1664             $scope.patron && 
1665             $scope.patron.profile && 
1666             $scope.patron.profile.usergroup() == 't'
1667         );
1668     }
1669
1670     $scope.new_address = function() {
1671         var addr = egCore.idl.toHash(new egCore.idl.aua());
1672         patronRegSvc.ingest_address($scope.patron, addr);
1673         addr.id = patronRegSvc.virt_id--;
1674         addr.isnew = true;
1675         addr.valid = true;
1676         addr.within_city_limits = true;
1677         addr.country = $scope.org_settings['ui.patron.default_country'];
1678         $scope.patron.addresses.push(addr);
1679     }
1680
1681     // keep deleted addresses out of the patron object so
1682     // they won't appear in the UI.  They'll be re-inserted
1683     // when the patron is updated.
1684     deleted_addresses = [];
1685     $scope.delete_address = function(id) {
1686
1687         if ($scope.patron.isnew &&
1688             $scope.patron.addresses.length == 1 &&
1689             $scope.org_settings['ui.patron.registration.require_address']) {
1690             egAlertDialog.open(egCore.strings.REG_ADDR_REQUIRED);
1691             return;
1692         }
1693
1694         var addresses = [];
1695         angular.forEach($scope.patron.addresses, function(addr) {
1696             if (addr.id == id) {
1697                 if (id > 0) {
1698                     addr.isdeleted = true;
1699                     deleted_addresses.push(addr);
1700                 }
1701             } else {
1702                 addresses.push(addr);
1703             }
1704         });
1705         $scope.patron.addresses = addresses;
1706     } 
1707
1708     $scope.approve_pending_address = function(addr) {
1709
1710         egCore.net.request(
1711             'open-ils.actor',
1712             'open-ils.actor.user.pending_address.approve',
1713             egCore.auth.token(), addr.id
1714         ).then(function(replaced_id) {
1715             var evt = egCore.evt.parse(replaced_id);
1716             if (evt) { alert(evt); return; }
1717
1718             // Remove the pending address and the replaced address
1719             // from the local list of patron addresses.
1720             var addresses = [];
1721             angular.forEach($scope.patron.addresses, function(a) {
1722                 if (a.id != addr.id && a.id != replaced_id) {
1723                     addresses.push(a);
1724                 }
1725             });
1726             $scope.patron.addresses = addresses;
1727
1728             // Fetch a fresh copy of the modified address from the server.
1729             // and add it back to the list.
1730             egCore.pcrud.retrieve('aua', replaced_id, {}, {authoritative: true})
1731             .then(null, null, function(new_addr) {
1732                 new_addr = egCore.idl.toHash(new_addr);
1733                 patronRegSvc.ingest_address($scope.patron, new_addr);
1734                 $scope.patron.addresses.push(new_addr);
1735             });
1736         });
1737     }
1738
1739     $scope.post_code_changed = function(addr) { 
1740         egCore.net.request(
1741             'open-ils.search', 'open-ils.search.zip', addr.post_code)
1742         .then(function(resp) {
1743             if (!resp) return;
1744             if (resp.city) addr.city = resp.city;
1745             if (resp.state) addr.state = resp.state;
1746             if (resp.county) addr.county = resp.county;
1747             if (resp.alert) alert(resp.alert);
1748         });
1749     }
1750
1751     $scope.new_waiver_entry = function() {
1752         var waiver = egCore.idl.toHash(new egCore.idl.aupw());
1753         patronRegSvc.ingest_waiver_entry($scope.patron, waiver);
1754         waiver.id = patronRegSvc.virt_id--;
1755         waiver.isnew = true;
1756         $scope.patron.waiver_entries.push(waiver);
1757     }
1758
1759     deleted_waiver_entries = [];
1760     $scope.delete_waiver_entry = function(waiver_entry) {
1761         if (waiver_entry.id > 0) {
1762             waiver_entry.isdeleted = true;
1763             deleted_waiver_entries.push(waiver_entry);
1764         }
1765         var index = $scope.patron.waiver_entries.indexOf(waiver_entry);
1766         $scope.patron.waiver_entries.splice(index, 1);
1767     }
1768
1769     $scope.replace_card = function() {
1770         $scope.patron.card.active = false;
1771         $scope.patron.card.ischanged = true;
1772         $scope.disable_bc = false;
1773
1774         var new_card = egCore.idl.toHash(new egCore.idl.ac());
1775         new_card.id = patronRegSvc.virt_id--;
1776         new_card.isnew = true;
1777         new_card.active = true;
1778         new_card._primary = 'on';
1779         $scope.patron.card = new_card;
1780
1781         // Remove any previous attempts to replace the card, since they
1782         // may be incomplete or created by accident.
1783         $scope.patron.cards =
1784             $scope.patron.cards.filter(function(c) {return !c.isnew})
1785         $scope.patron.cards.push(new_card);
1786     }
1787
1788     $scope.day_phone_changed = function(phone) {
1789         if (phone && $scope.patron.isnew && 
1790             $scope.org_settings['patron.password.use_phone']) {
1791             $scope.patron.passwd = phone.substr(-4);
1792         }
1793     }
1794
1795     $scope.barcode_changed = function(bc) {
1796         if (!bc) return;
1797         $scope.dupe_barcode = false;
1798         egCore.net.request(
1799             'open-ils.actor',
1800             'open-ils.actor.barcode.exists',
1801             egCore.auth.token(), bc
1802         ).then(function(resp) {
1803             if (resp == '1') { // duplicate card
1804                 $scope.dupe_barcode = true;
1805                 console.log('duplicate barcode detected: ' + bc);
1806             } else {
1807                 if (!$scope.patron.usrname)
1808                     $scope.patron.usrname = bc;
1809                 // No dupe -- A-OK
1810             }
1811         });
1812     }
1813
1814     $scope.cards_dialog = function() {
1815         $uibModal.open({
1816             templateUrl: './circ/patron/t_patron_cards_dialog',
1817             backdrop: 'static',
1818             controller: 
1819                    ['$scope','$uibModalInstance','cards','perms','patron',
1820             function($scope , $uibModalInstance , cards , perms , patron) {
1821                 // scope here is the modal-level scope
1822                 $scope.args = {cards : cards, primary_barcode : null};
1823                 angular.forEach(cards, function(card) {
1824                     if (card.id == patron.card.id) {
1825                         $scope.args.primary_barcode = card.id;
1826                     }
1827                 });
1828                 $scope.perms = perms;
1829                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1830                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1831             }],
1832             resolve : {
1833                 cards : function() {
1834                     // scope here is the controller-level scope
1835                     return $scope.patron.cards;
1836                 },
1837                 perms : function() {
1838                     return $scope.perms;
1839                 },
1840                 patron : function() {
1841                     return $scope.patron;
1842                 }
1843             }
1844         }).result.then(
1845             function(args) {
1846                 angular.forEach(args.cards, function(card) {
1847                     card.ischanged = true; // assume cards need updating, OK?
1848                     if (card.id == args.primary_barcode) {
1849                         $scope.patron.card = card;
1850                         card._primary = true;
1851                     } else {
1852                         card._primary = false;
1853                     }
1854                 });
1855             }
1856         );
1857     }
1858
1859     $scope.set_addr_type = function(addr, type) {
1860         var addrs = $scope.patron.addresses;
1861         if (addr['_is_'+type]) {
1862             angular.forEach(addrs, function(a) {
1863                 if (a.id != addr.id) a['_is_'+type] = false;
1864             });
1865         } else {
1866             // unchecking mailing/billing means we have to randomly
1867             // select another address to fill that role.  Select the
1868             // first address in the list (that does not match the
1869             // modifed address)
1870             for (var i = 0; i < addrs.length; i++) {
1871                 if (addrs[i].id != addr.id) {
1872                     addrs[i]['_is_' + type] = true;
1873                     break;
1874                 }
1875             }
1876         }
1877     }
1878
1879
1880     // Translate hold notify preferences from the form/scope back into a 
1881     // single user setting value for opac.hold_notify.
1882     function compress_hold_notify() {
1883         var hold_notify_methods = [];
1884         if ($scope.hold_notify_type.phone) {
1885             hold_notify_methods.push('phone');
1886         }
1887         if ($scope.hold_notify_type.email) {
1888             hold_notify_methods.push('email');
1889         }
1890         if ($scope.hold_notify_type.sms) {
1891             hold_notify_methods.push('sms');
1892         }
1893
1894         $scope.user_settings['opac.hold_notify'] = hold_notify_methods.join(':');
1895     }
1896
1897     // dialog for selecting additional permission groups
1898     $scope.secondary_groups_dialog = function() {
1899         $uibModal.open({
1900             templateUrl: './circ/patron/t_patron_groups_dialog',
1901             backdrop: 'static',
1902             controller: 
1903                    ['$scope','$uibModalInstance','linked_groups','pgt_depth',
1904             function($scope , $uibModalInstance , linked_groups , pgt_depth) {
1905
1906                 $scope.pgt_depth = pgt_depth;
1907                 $scope.args = {
1908                     linked_groups : linked_groups,
1909                     edit_profiles : patronRegSvc.edit_profiles,
1910                     new_profile   : patronRegSvc.edit_profiles[0]
1911                 };
1912
1913                 // add a new group to the linked groups list
1914                 $scope.link_group = function($event, grp) {
1915                     var found = false; // avoid duplicates
1916                     angular.forEach($scope.args.linked_groups, 
1917                         function(g) {if (g.id() == grp.id()) found = true});
1918                     if (!found) $scope.args.linked_groups.push(grp);
1919                     $event.preventDefault(); // avoid close
1920                 }
1921
1922                 // remove a group from the linked groups list
1923                 $scope.unlink_group = function($event, grp) {
1924                     $scope.args.linked_groups = 
1925                         $scope.args.linked_groups.filter(function(g) {
1926                         return g.id() != grp.id()
1927                     });
1928                     $event.preventDefault(); // avoid close
1929                 }
1930
1931                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1932                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1933             }],
1934             resolve : {
1935                 linked_groups : function() { return $scope.patron.groups },
1936                 pgt_depth : function() { return $scope.pgt_depth }
1937             }
1938         }).result.then(
1939             function(args) {
1940
1941                 if ($scope.patron.isnew) {
1942                     // groups must be linked for new patrons after the
1943                     // patron is created.
1944                     $scope.patron.groups = args.linked_groups;
1945                     return;
1946                 }
1947
1948                 // update links groups for existing users in real time.
1949                 var ids = args.linked_groups.map(function(g) {return g.id()});
1950                 patronRegSvc.apply_secondary_groups($scope.patron.id, ids)
1951                 .then(function(success) {
1952                     if (success)
1953                         $scope.patron.groups = args.linked_groups;
1954                 });
1955             }
1956         );
1957     }
1958
1959     function extract_hold_notify() {
1960         var p = $scope.patron;
1961
1962         // get the user's opac.hold_notify setting
1963         var notify = $scope.user_settings['opac.hold_notify'];
1964
1965         // if it's not set, use the default opac.hold_notify value
1966         if (!notify && !(notify === '')) {
1967             var notify_stype = $scope.user_setting_types['opac.hold_notify'];
1968             if (notify_stype && notify_stype.reg_default() !== undefined && notify_stype.reg_default() !== null) {
1969                 notify = notify_stype.reg_default();
1970             } else {
1971                 // no setting and no default: set phone and email to true
1972                 notify = 'phone:email';
1973             }
1974         }
1975
1976         $scope.hold_notify_type.phone = Boolean(notify.match(/phone/));
1977         $scope.hold_notify_type.email = Boolean(notify.match(/email/));
1978         $scope.hold_notify_type.sms = Boolean(notify.match(/sms/));
1979
1980         // stores original loaded values for comparison later
1981         for (var k in $scope.hold_notify_type){
1982             var val = $scope.hold_notify_type[k];
1983
1984             if ($scope.hold_notify_type.hasOwnProperty(k)){
1985                 $scope.hold_notify_observer[k] = {old : val, newval: null};
1986             }
1987         }
1988
1989         // actual value from user
1990         $scope.hold_rel_contacts.day_phone = { old: p.day_phone, newval : null };
1991         $scope.hold_rel_contacts.other_phone = { old: p.other_phone, newval : null };
1992         $scope.hold_rel_contacts.evening_phone = { old: p.evening_phone, newval : null };
1993         // from user_settings
1994         $scope.hold_rel_contacts.default_phone = { old: $scope.user_settings['opac.default_phone'], newval : null };
1995         $scope.hold_rel_contacts.default_sms = { old: $scope.user_settings['opac.default_sms_notify'], newval : null };
1996         $scope.hold_rel_contacts.default_sms_carrier_id = { old: $scope.user_settings['opac.default_sms_carrier'], newval : null };
1997
1998     }
1999
2000     function normalizePhone(number){
2001         // normalize phone # for comparison, only digits
2002         if (number == null || number == undefined) return '';
2003         
2004         var regex = /[^\d]/g;
2005         return number.replace(regex, '');
2006     }
2007
2008     $scope.invalidate_field = function(field) {
2009         patronRegSvc.invalidate_field($scope.patron, field).then(function() {
2010             $scope.handle_field_changed($scope.patron, field);
2011         });
2012     }
2013
2014     $scope.send_test_email = function() {
2015         patronRegSvc.send_test_message($scope.patron.id, 'au.email.test').then(function(res) {
2016             if (res && res.template_output() && res.template_output().is_error() == 'f') {
2017                  ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2018             } else {
2019                 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2020                 if (res) console.log(res);
2021             }
2022         });
2023     }
2024
2025     $scope.send_test_sms = function() {
2026         patronRegSvc.send_test_message($scope.patron.id, 'au.sms_text.test').then(function(res) {
2027             if (res && res.template_output() && res.template_output().is_error() == 'f') {
2028                  ngToast.success(egCore.strings.TEST_NOTIFY_SUCCESS);
2029             } else {
2030                 ngToast.warning(egCore.strings.TEST_NOTIFY_FAIL);
2031                 if (res) console.log(res);
2032             }
2033         });
2034     }
2035
2036     address_alert = function(addr) {
2037         var args = {
2038             street1: addr.street1,
2039             street2: addr.street2,
2040             city: addr.city,
2041             state: addr.state,
2042             county: addr.county,
2043             country: addr.country,
2044             post_code: addr.post_code,
2045             mailing_address: addr._is_mailing,
2046             billing_address: addr._is_billing
2047         }
2048
2049         egCore.net.request(
2050             'open-ils.actor',
2051             'open-ils.actor.address_alert.test',
2052             egCore.auth.token(), egCore.auth.user().ws_ou(), args
2053             ).then(function(res) {
2054                 $scope.address_alerts = res;
2055         });
2056     }
2057
2058     $scope.dupe_value_changed = function(type, value) {
2059         if (!$scope.dupe_search_encoded)
2060             $scope.dupe_search_encoded = {};
2061
2062         $scope.dupe_counts[type] = 0;
2063
2064         patronRegSvc.dupe_patron_search($scope.patron, type, value)
2065         .then(function(res) {
2066             $scope.dupe_counts[type] = res.count;
2067             if (res.count) {
2068                 $scope.dupe_search_encoded[type] = 
2069                     encodeURIComponent(js2JSON(res.search));
2070             } else {
2071                 $scope.dupe_search_encoded[type] = '';
2072             }
2073         });
2074     }
2075
2076     $scope.handle_home_org_changed = function() {
2077         org_id = $scope.patron.home_ou.id();
2078         patronRegSvc.has_perms_for_org(org_id).then(function(map) {
2079             angular.forEach(map, function(v, k) { $scope.perms[k] = v });
2080         });
2081     }
2082
2083     $scope.handle_pulib_changed = function(org) {
2084         if (!$scope.user_settings) return; // still rendering
2085         $scope.user_settings['opac.default_pickup_location'] = org.id();
2086     }
2087
2088     // This is called with every character typed in a form field,
2089     // since that's the only way to gaurantee something has changed.
2090     // See handle_field_changed for ng-change vs. ng-blur.
2091     $scope.field_modified = function() {
2092         // Call attach with every field change, regardless of whether
2093         // it's been called before.  This will allow for re-attach after
2094         // the user clicks through the unload warning. egUnloadPrompt
2095         // will ensure we only attach once.
2096         egUnloadPrompt.attach($scope);
2097     }
2098
2099     // also monitor when form is changed *by the user*, as using
2100     // an ng-change handler doesn't work with eg-date-input
2101     $scope.$watch('reg_form.$pristine', function(newVal, oldVal) {
2102         if (!newVal) egUnloadPrompt.attach($scope);
2103     });
2104
2105     // username regex (if present) must be removed any time
2106     // the username matches the barcode to avoid firing the
2107     // invalid field handlers.
2108     function apply_username_regex() {
2109         var regex = $scope.org_settings['opac.username_regex'];
2110         if (regex) {
2111             if ($scope.patron.card.barcode) {
2112                 // username must match the regex or the barcode
2113                 field_patterns.au.usrname = 
2114                     new RegExp(
2115                         regex + '|^' + $scope.patron.card.barcode + '$');
2116             } else {
2117                 // username must match the regex
2118                 field_patterns.au.usrname = new RegExp(regex);
2119             }
2120         } else {
2121             // username can be any format.
2122             field_patterns.au.usrname = new RegExp('.*');
2123         }
2124     }
2125
2126     // obj could be the patron, an address, etc.
2127     // This is called any time a form field achieves then loses focus.
2128     // It does not necessarily mean the field has changed.
2129     // The alternative is ng-change, but it's called with each character
2130     // typed, which would be overkill for many of the actions called here.
2131     $scope.handle_field_changed = function(obj, field_name) {
2132         var cls = obj.classname; // set by egIdl
2133         var value = obj[field_name];
2134
2135         console.debug('changing field ' + field_name + ' to ' + value);
2136
2137         switch (field_name) {
2138             case 'day_phone' :
2139                 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.day_phone.old)){
2140                     $scope.hold_rel_contacts.day_phone.newval = value;
2141                 }
2142                 if ($scope.patron.day_phone && 
2143                     $scope.patron.isnew && 
2144                     $scope.org_settings['patron.password.use_phone']) {
2145                     $scope.patron.passwd = $scope.patron.day_phone.substr(-4);
2146                 }
2147                 $scope.dupe_value_changed(field_name, value);
2148                 break;
2149             case 'evening_phone' :
2150                 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.evening_phone.old)){
2151                     $scope.hold_rel_contacts.evening_phone.newval = value;
2152                 }
2153                 $scope.dupe_value_changed(field_name, value);
2154                 break;
2155             case 'other_phone' : 
2156                 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.other_phone.old)){
2157                     $scope.hold_rel_contacts.other_phone.newval = value;
2158                 }
2159                 $scope.dupe_value_changed(field_name, value);
2160                 break;
2161             case 'ident_value':
2162             case 'ident_value2':
2163                 $scope.dupe_value_changed('ident', value);
2164                 break;
2165
2166             case 'first_given_name':
2167             case 'family_name':
2168                 $scope.dupe_value_changed('name', value);
2169                 break;
2170
2171             case 'email':
2172                 $scope.dupe_value_changed('email', value);
2173                 break;
2174
2175             case 'street1':
2176             case 'street2':
2177             case 'city':
2178                 // dupe search on address wants the address object as the value.
2179                 $scope.dupe_value_changed('address', obj);
2180                 address_alert(obj);
2181                 break;
2182
2183             case 'post_code':
2184                 $scope.post_code_changed(obj);
2185                 break;
2186
2187             case 'usrname':
2188                 patronRegSvc.check_dupe_username(value)
2189                 .then(function(yes) {$scope.dupe_username = Boolean(yes)});
2190                 break;
2191
2192             case 'barcode':
2193                 // TODO: finish barcode_changed handler.
2194                 $scope.barcode_changed(value);
2195                 apply_username_regex();
2196                 break;
2197             case 'opac.default_phone':
2198                 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_phone.old)){
2199                     $scope.hold_rel_contacts.default_phone.newval = value;
2200                 }
2201                 break;
2202             case 'opac.default_sms_notify':
2203                 if (normalizePhone(value) !== normalizePhone($scope.hold_rel_contacts.default_sms.old)){
2204                     $scope.hold_rel_contacts.default_sms.newval = value;
2205                 }
2206                 break;
2207             case 'opac.default_sms_carrier':
2208                 if (value !== $scope.hold_rel_contacts.default_sms_carrier_id.old){
2209                     $scope.hold_rel_contacts.default_sms_carrier_id.newval = value;
2210                 }
2211                 break;
2212         }
2213     }
2214
2215     // patron.juvenile is set to true if the user was born after
2216     function maintain_juvenile_flag() {
2217         if ( !($scope.patron && $scope.patron.dob) ) return;
2218
2219         var juv_interval = 
2220             $scope.org_settings['global.juvenile_age_threshold'] 
2221             || '18 years';
2222
2223         var base = new Date();
2224
2225         base.setTime(base.getTime() - 
2226             Number(egCore.date.intervalToSeconds(juv_interval) + '000'));
2227
2228         $scope.patron.juvenile = ($scope.patron.dob > base);
2229     }
2230
2231     // returns true (disable) for orgs that cannot have users.
2232     $scope.disable_home_org = function(org_id) {
2233         if (!org_id) return;
2234         var org = egCore.org.get(org_id);
2235         return (
2236             org &&
2237             org.ou_type() &&
2238             org.ou_type().can_have_users() == 'f'
2239         );
2240     }
2241
2242     // returns true (disable) for orgs that cannot have vols (for holds pickup)
2243     $scope.disable_pulib = function(org_id) {
2244         if (!org_id) return;
2245         return !egCore.org.CanHaveVolumes(org_id);
2246     }
2247
2248     // Returns true if attempting to edit self, but perms don't allow
2249     $scope.edit_passthru.self_edit_disallowed = function() {
2250         if ($scope.patron.id
2251             && $scope.patron.id == egCore.auth.user().id()
2252             && !$scope.perms.EDIT_SELF_IN_CLIENT
2253         ) return true;
2254         return false;
2255     }
2256
2257     // Returns true if attempting to edit a user without appropriate group application perms
2258     $scope.edit_passthru.group_edit_disallowed = function() {
2259         if ( $scope.patron.profile
2260              && patronRegSvc
2261                 .edit_profiles
2262                 .filter(function(p) {
2263                     return $scope.patron.profile.id() == p.id();
2264                 }).length == 0
2265         ) return true;
2266         return false;
2267     }
2268
2269     // Returns true if the Save and Save & Clone buttons should be disabled.
2270     $scope.edit_passthru.hide_save_actions = function() {
2271         if ($scope.edit_passthru.self_edit_disallowed()) return true;
2272         if ($scope.edit_passthru.group_edit_disallowed()) return true;
2273
2274         return $scope.patron.isnew ?
2275             !$scope.perms.CREATE_USER : 
2276             !$scope.perms.UPDATE_USER;
2277     }
2278
2279     // Returns true if any input elements are tagged as invalid
2280     // via Angular patterns or required attributes.
2281     function form_has_invalid_fields() {
2282         return $('#patron-reg-container .ng-invalid').length > 0;
2283     }
2284
2285     function form_is_incomplete() {
2286         return (
2287             $scope.dupe_username ||
2288             $scope.dupe_barcode ||
2289             form_has_invalid_fields()
2290         );
2291
2292     }
2293
2294     $scope.edit_passthru.save = function(save_args) {
2295         if (!save_args) save_args = {};
2296
2297         if (form_is_incomplete()) {
2298             // User has not provided valid values for all required fields.
2299             return egAlertDialog.open(egCore.strings.REG_INVALID_FIELDS);
2300         }
2301
2302         // remove page unload warning prompt
2303         egUnloadPrompt.clear();
2304
2305         // toss the deleted addresses back into the patron's list of
2306         // addresses so it's included in the update
2307         $scope.patron.addresses = 
2308             $scope.patron.addresses.concat(deleted_addresses);
2309         
2310         // ditto for waiver entries
2311         $scope.patron.waiver_entries = 
2312             $scope.patron.waiver_entries.concat(deleted_waiver_entries);
2313
2314         compress_hold_notify();
2315
2316         var updated_user;
2317
2318         patronRegSvc.save_user($scope.patron)
2319         .then(function(new_user) { 
2320             if (new_user && new_user.classname) {
2321                 updated_user = new_user;
2322                 return patronRegSvc.save_user_settings(
2323                     new_user, $scope.user_settings); 
2324             } else {
2325                 var evt = egCore.evt.parse(new_user);
2326
2327                 if (evt && evt.textcode == 'XACT_COLLISION') {
2328                     return egAlertDialog.open(
2329                         egCore.strings.PATRON_EDIT_COLLISION).result;
2330                 }
2331
2332                 // debug only -- should not get here.
2333                 alert('Patron update failed. \n\n' + js2JSON(new_user));
2334             }
2335
2336         }).then(function() {
2337
2338             // only remove the staged user if the update succeeded.
2339             if (updated_user) 
2340                 return patronRegSvc.remove_staged_user();
2341
2342             return $q.when();
2343
2344         }).then(function() {
2345
2346             // linked groups for new users must be created after the new
2347             // user is created.
2348             if ($scope.patron.isnew && 
2349                 $scope.patron.groups && $scope.patron.groups.length) {
2350                 var ids = $scope.patron.groups.map(function(g) {return g.id()});
2351                 return patronRegSvc.apply_secondary_groups(updated_user.id(), ids)
2352             }
2353             return $q.when();
2354
2355         }).then(findChangedFieldsAffectedHolds)
2356         .then(function(changed_fields_plus_holds) {
2357             var needModal = changed_fields_plus_holds[0] && changed_fields_plus_holds[0].length > 0;
2358             return needModal
2359                 ? $scope.update_holds_notify_modal(changed_fields_plus_holds[0])
2360                 : $q.when(); // nothing changed, continue
2361         }).then(function() {
2362             if (updated_user) {
2363                 egWorkLog.record(
2364                     $scope.patron.isnew
2365                     ? egCore.strings.EG_WORK_LOG_REGISTERED_PATRON
2366                     : egCore.strings.EG_WORK_LOG_EDITED_PATRON, {
2367                         'action' : $scope.patron.isnew ? 'registered_patron' : 'edited_patron',
2368                         'patron_id' : updated_user.id()
2369                     }
2370                 );
2371             }
2372
2373             // reloading the page means potentially losing some information
2374             // (e.g. last patron search), but is the only way to ensure all
2375             // components are properly updated to reflect the modified patron.
2376             if (updated_user && save_args.clone) {
2377                 // open a separate tab for registering a new 
2378                 // patron from our cloned data.
2379                 var url = 'https://' 
2380                     + $window.location.hostname 
2381                     + egCore.env.basePath 
2382                     + '/circ/patron/register/clone/' 
2383                     + updated_user.id();
2384                 $window.open(url, '_blank').focus();
2385
2386             } else if ($window.location.href.indexOf('stage') > -1 ){
2387                 // we're here after deleting a self-reg staged user.
2388                 // Just close tab, since refresh won't find staged user
2389                 $timeout(function(){
2390                     if (typeof BroadcastChannel != 'undefined') {
2391                         var bChannel = new BroadcastChannel("eg.pending_usr.update");
2392                         bChannel.postMessage({
2393                             usr: egCore.idl.toHash(updated_user)
2394                         });
2395                     }
2396
2397                     $window.close();
2398                 });
2399             } else {
2400                 // reload the current page
2401                 $window.location.href = location.href;
2402             }
2403         });
2404     }
2405     
2406     var phone_inputs = ["day_phone", "evening_phone","other_phone", "default_phone"];
2407     var sms_inputs = ["default_sms", "default_sms_carrier_id"];
2408     var method_prefs = ["sms_notify", "phone_notify", "email_notify"];
2409     var groupBy = function(xs, key){
2410         return xs.reduce(function(rv, x){
2411             (rv[x[key]] = rv[x[key]] || []).push(x);
2412             return rv;
2413         }, {});
2414     };
2415
2416     function findChangedFieldsAffectedHolds(){
2417     
2418         var changed_hold_fields = [];
2419
2420         var default_phone_changed = false;
2421         var default_sms_carrier_changed = false;
2422         var default_sms_changed = false;
2423         for (var c in $scope.hold_rel_contacts){
2424             var newinput = $scope.hold_rel_contacts[c].newval;
2425             if ($scope.hold_rel_contacts.hasOwnProperty(c)
2426                 && newinput !== null // null means user has not provided a value in this session
2427                 && newinput != $scope.hold_rel_contacts[c].old){
2428                 var changed = $scope.hold_rel_contacts[c];
2429                 changed.name = c;
2430                 changed.isChecked = false;
2431                 changed_hold_fields.push(changed);
2432                 if (c === 'default_phone') default_phone_changed = true;
2433                 if (c === 'default_sms_carrier_id') default_sms_carrier_changed = true;
2434                 if (c === 'default_sms') default_sms_changed = true;
2435             }
2436         }
2437
2438         for (var c in $scope.hold_notify_observer){
2439             var newinput = $scope.hold_notify_observer[c].newval;
2440             if ($scope.hold_notify_observer.hasOwnProperty(c)
2441                 && newinput !== null // null means user has not provided a value in this session
2442                 && newinput != $scope.hold_notify_observer[c].old){
2443                 var changed = $scope.hold_notify_observer[c];
2444                 changed.name = c + "_notify";
2445                 changed.isChecked = false;
2446                 changed_hold_fields.push(changed);
2447
2448                 // if we're turning on phone notifications, offer to update to the
2449                 // current default number
2450                 if (c === 'phone' && $scope.user_settings['opac.default_phone'] && newinput && !default_phone_changed) {
2451                     changed_hold_fields.push({
2452                         name: 'default_phone',
2453                         old: 'nosuch',
2454                         newval: $scope.user_settings['opac.default_phone'],
2455                         isChecked: false
2456                     });
2457                 }
2458                 // and similarly for SMS
2459                 if (c === 'sms' && $scope.user_settings['opac.default_sms_carrier'] && newinput && !default_sms_carrier_changed) {
2460                     changed_hold_fields.push({
2461                         name: 'default_sms_carrier_id',
2462                         old: -1,
2463                         newval: $scope.user_settings['opac.default_sms_carrier'],
2464                         isChecked: false
2465                     });
2466                 }
2467                 if (c === 'sms' && $scope.user_settings['opac.default_sms_notify'] && newinput && !default_sms_changed) {
2468                     changed_hold_fields.push({
2469                         name: 'default_sms',
2470                         old: 'nosuch',
2471                         newval: $scope.user_settings['opac.default_sms_notify'],
2472                         isChecked: false
2473                     });
2474                 }
2475             }
2476         }
2477
2478         var promises = [];
2479         angular.forEach(changed_hold_fields, function(c){
2480             promises.push(egCore.net.request('open-ils.circ',
2481             'open-ils.circ.holds.retrieve_by_notify_staff',
2482             egCore.auth.token(),
2483             $scope.patron.id,
2484             c.name.includes('notify') || c.name.includes('carrier') ? c.old : c.newval,
2485             c.name)
2486                 .then(function(affected_holds){
2487                     if(!affected_holds || affected_holds.length < 1){
2488                         // no holds affected - remove change from list
2489                         var p = changed_hold_fields.indexOf(c);
2490                         changed_hold_fields.splice(p, 1);
2491                     } else {
2492                         c.affects = affected_holds;
2493                         //c.groups = {};
2494                         //angular.forEach(c.affects, function(h){
2495                         //    c.groups[]
2496                         //});
2497                         if (!c.name.includes("notify")){
2498                             if (c.name === "default_sms_carrier_id") {
2499                                 c.groups = groupBy(c.affects,'sms_carrier');
2500                             } else {
2501                                 c.groups = groupBy(c.affects, c.name.includes('_phone') ? 'phone_notify':'sms_notify');
2502                             }
2503                         }
2504                     }
2505                     return $q.when(changed_hold_fields);
2506                 })
2507             );
2508         });
2509
2510         return $q.all(promises);
2511     }
2512
2513     $scope.update_holds_notify_modal = function(changed_hold_fields){
2514         // open modal after-save, pre-reload modal to deal with updated hold notification stuff
2515         if ($scope.patron.isnew || changed_hold_fields.length < 1){
2516             return $q.when();
2517         }
2518
2519         return $uibModal.open({
2520             templateUrl: './circ/patron/t_hold_notify_update',
2521             backdrop: 'static',
2522             controller:
2523                        ['$scope','$uibModalInstance','changed_fields','patron','carriers','def_carrier_id','default_phone','default_sms',
2524                 function($scope , $uibModalInstance , changed_fields , patron,  carriers,  def_carrier_id , default_phone , default_sms) {
2525                 // local modal scope
2526                 $scope.ch_fields = changed_fields;
2527                 $scope.focusMe = true;
2528                 $scope.ok = function(msg) {
2529
2530                     // Need to do this so the page will reload automatically
2531                     if (msg == 'no-update') return $uibModalInstance.close();
2532
2533                     //var selectedChanges = $scope.changed_fields.filter(function(c) {
2534                     //    return c.isChecked;
2535                     //});
2536                     var selectedChanges = [];
2537                     angular.forEach($scope.ch_fields, function(f){
2538                         if (f.name == 'phone_notify' && f.newval && f.isChecked) {
2539                             // convert to default_phone change
2540                             f.sel_hids = f.affects.map(function(h){ return h.id});
2541                             f.newval = default_phone;
2542                             f.name = 'default_phone';
2543                             selectedChanges.push(f);
2544                         } else if (f.name == 'sms_notify' && f.newval && f.isChecked) {
2545                             // convert to default_sms change
2546                             f.sel_hids = f.affects.map(function(h){ return h.id});
2547                             f.newval = default_sms;
2548                             f.name = 'default_sms';
2549                             selectedChanges.push(f);
2550                         } else if (f.name.includes('notify') || f.name.includes('carrier')){
2551                             if (f.isChecked){
2552                                 f.sel_hids = f.affects.map(function(h){ return h.id});
2553                                 selectedChanges.push(f);
2554                             }
2555                         } else {
2556                             // this is the sms or phone, so look in the groups obj
2557                             f.sel_hids = [];
2558                             for (var k in f.groups){
2559                                 if (f.groups.hasOwnProperty(k)){
2560                                     var sel_holds = f.groups[k].filter(function(h){
2561                                         return h.isChecked;
2562                                     });
2563                                     
2564                                     var hids = sel_holds.map(function(h){ return h.id});
2565                                     f.sel_hids.push.apply(f.sel_hids, hids);
2566                                 }
2567                             }
2568
2569                             if (f.sel_hids.length > 0) selectedChanges.push(f);
2570                         }
2571                     });
2572
2573
2574                     // call method to update holds for each change
2575                     var chain = $q.when();
2576                     angular.forEach(selectedChanges, function(c){
2577                         var carrierId = c.name.includes('default_sms') ? Number(def_carrier_id) : null;
2578                         chain = chain.then(function() {
2579                             return egCore.net.request('open-ils.circ',
2580                                     'open-ils.circ.holds.batch_update_holds_by_notify_staff', egCore.auth.token(),
2581                                     patron.id,
2582                                     c.sel_hids,
2583                                     c.old, // TODO: for number changes, old val is effectively moot
2584                                     c.newval,
2585                                     c.name,
2586                                     carrierId).then(function(okList){ console.log(okList) });
2587                         });
2588                     });
2589
2590                     // carry out the updates and close modal
2591                     chain.finally(function(){ $uibModalInstance.close() });
2592                 }
2593
2594                 $scope.cancel = function () { $uibModalInstance.dismiss() }
2595
2596                 $scope.isNumberCh = function(c){
2597                     return !(c.name.includes('notify') || c.name.includes('carrier'));
2598                 }
2599
2600                 $scope.chgCt = 0;
2601                 $scope.groupChanged = function(ch_f, grpK){
2602                     var holdArr = ch_f.groups[grpK];
2603                     if (holdArr && holdArr.length > 0){
2604                         angular.forEach(holdArr, function(h){
2605                             if (h.isChecked) { h.isChecked = !h.isChecked; $scope.chgCt-- }
2606                             else { h.isChecked = true; $scope.chgCt++ }
2607                         });
2608                     }
2609                 }
2610                 
2611                 $scope.nonGrpChanged = function(field_ch){
2612                     if (field_ch.isChecked) $scope.chgCt++;
2613                     else $scope.chgCt--;
2614                 };
2615
2616                 // use this function as a keydown handler on form
2617                 // elements that should not submit the form on enter.
2618                 $scope.preventSubmit = function($event) {
2619                     if ($event.keyCode == 13)
2620                         $event.preventDefault();
2621                 }
2622
2623                 $scope.prettyCarrier = function(carrierId){
2624                     var sms_carrierObj = carriers.find(function(c){ return c.id == carrierId});
2625                     return sms_carrierObj.name;
2626                 };
2627                 $scope.prettyBool = function(v){
2628                     return v ? 'YES' : 'NO';
2629                 };
2630             }],
2631             resolve : {
2632                     changed_fields : function(){ return changed_hold_fields },
2633                     patron : function(){ return $scope.patron },
2634                     def_carrier_id : function(){
2635                                        var d = $scope.hold_rel_contacts.default_sms_carrier_id;
2636                                        return d.newval ? d.newval : d.old;
2637                                     },
2638                     default_phone : function() {
2639                                         return ($scope.hold_rel_contacts.default_phone.newval) ?
2640                                                     $scope.hold_rel_contacts.default_phone.newval :
2641                                                     $scope.hold_rel_contacts.default_phone.old;
2642                                     },
2643                     default_sms : function() {
2644                                         return ($scope.hold_rel_contacts.default_sms.newval) ?
2645                                                     $scope.hold_rel_contacts.default_sms.newval :
2646                                                     $scope.hold_rel_contacts.default_sms.old;
2647                                     },
2648                     carriers : function(){ return $scope.sms_carriers.map(function(c){ return egCore.idl.toHash(c) }) }
2649                 }
2650         }).result;
2651     }
2652     
2653     $scope.edit_passthru.print = function() {
2654         var print_data = {patron : $scope.patron}
2655
2656         return egCore.print.print({
2657             context : 'default',
2658             template : 'patron_data',
2659             scope : print_data
2660         });
2661     }
2662 }])