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