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