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