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