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