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