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