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