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