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