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