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