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