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